如何使用Ninject Conventions Extension进行绑定?

我喜欢使用Ninject自动绑定绑定波纹管代码。 是否可以在单个项目中同时使用手动和自动绑定? 让我们采取波纹管手动绑定,我希望通过自动绑定实现。 请告诉我如何实现这一目标。

  1. kernel.Bind().ToSelf().InRequestScope();

  2. kernel.Bind<IUnitOfWork>().To<UnitOfWork>();

Bellow所有接口都inheritance自基础接口: IRepository

3。 kernel.Bind().To();

4。 kernel.Bind().To();

5。 kernel.Bind().To().WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey)

额外

我是否需要为多个类编写.Exclude()如果我需要这样做的话

.Exclude() .Exclude() .Exclude()

并且对于1和2是否需要单独的手动绑定? 或者1可以使用BindToSelf()' and .Configure(b => b.InRequestScope())`完成

是的,可以在同一个项目中使用约定绑定和单个绑定,即使在同一个模块中也是如此。

 IBindingRoot.Bind(x => x .FromThisAssembly() .IncludingNonePublicTypes() .SelectAllClasses() .InheritedFrom(typeof(IRepository<>)) .BindDefaultInterface() .Configure(y => y.InRequestScope())); 

但是,您将无法将构造函数参数传递给特定的类。 所以我建议用一个包装访问配置的接口替换构造函数参数(无论如何这是一个很好的设计)。

或者你也可以这样做:

 IBindingRoot.Bind(x => x .FromThisAssembly() .IncludingNonePublicTypes() .SelectAllClasses() .InheritedFrom(typeof(IRepository<>)) .Exclude() .BindDefaultInterface() .Configure(y => y.InRequestScope())); IBindingRoot.Bind().To) .WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey) .InRequestScope(); 

– >您可以为每个存储库执行一个.Exclude() ,其中约定绑定是不够的。 对于每个exlucded绑定,您必须自己指定一个。 如上所述:对所有实现IRepository<>类的条件绑定, 除了 MessageRepository类,它获取自己的绑定。

另外看看这个: https : //github.com/ninject/ninject.extensions.conventions/wiki/Projecting-Services-to-Bind

附录:请注意,您可以指定多个常规​​绑定,例如:

 IBindingRoot.Bind(x => x .FromThisAssembly() .SelectAllClasses() .InheritedFrom(typeof(IFoo)) .BindDefaultInterface() .Configure(y => y.InRequestScope())); IBindingRoot.Bind(x => x .FromThisAssembly() .SelectAllClasses() .InheritedFrom(typeof(IBar)) .BindToSelf() .Configure(y => y.InRequestScope())); 

完全没问题。

如果您只有少量例外,则上一个解决方案有效。 如果它们中有更多,你会得到许多没有意义的约定。

使用IBindingRoot.Rebind方法覆盖与约定已涵盖的绑定重叠的绑定。

 IBindingRoot.Bind(x => x .FromThisAssembly() .SelectAllClasses() .BindAllInterface()); IBindingRoot.Rebind().To) .WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey) .InRequestScope();