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

Shu*_*osh 2 c# dependency-injection ninject ninject-extensions ninject.web.mvc

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

  1. kernel.Bind<TestContext>().ToSelf().InRequestScope();

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

Bellow所有接口都继承自基础接口:IRepository <Model>

3. kernel.Bind<IUserRepository>().To<UserRepository>();

4. kernel.Bind<IAccountRepository>().To<AccountRepository>();

5. kernel.Bind<IMessageRepository>().To<MessageRepository>().WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey)

额外

我是否需要.Exclude<MessageRepository>()为多个类编写如果我需要这样做,如

.Exclude<ARepository>() .Exclude<BRepository>() .Exclude<CRepository>()

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

Bat*_*nit 5

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

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

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

或者你也可以这样做:

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

IBindingRoot.Bind<IMessageRepository>().To<MessageRepository>)
    .WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey)
    .InRequestScope();
Run Code Online (Sandbox Code Playgroud)

- >您可以.Exclude<TRepository>()为每个存储库执行一个,其中约定绑定是不够的.对于每个exlucded绑定,您必须自己指定一个.如上所述:IRepository<> 除了 class 之外的所有类的条件绑定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()));
Run Code Online (Sandbox Code Playgroud)

完全没问题.