【问题标题】:How to bind using Ninject Conventions Extension?如何使用 Ninject 约定扩展进行绑定?
【发布时间】:2014-02-27 17:07:05
【问题描述】:

我喜欢用 Ninject 自动绑定来绑定下面的代码。是否可以在单个项目中同时使用手动和自动绑定?让我们来看看手动绑定,我想用自动绑定来实现。请告诉我如何实现这一目标。

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

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

下面是从基础接口继承的所有接口:IRepository

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())` ?

【问题讨论】:

  • 对于 1. 和 2. 您应该使用单独的绑定。理论上,您可以使用约定并告诉它将整个程序集中的所有类绑定到其默认接口,但从中长期来看,这将导致比指定具体的单一绑定更复杂。另请注意,您可以使用多个常规绑定!

标签: c# dependency-injection ninject ninject.web.mvc ninject-extensions


【解决方案1】:

是的,可以在同一个项目中使用约定绑定和单一绑定,甚至在同一个模块中。

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<MessageRepository>()
    .BindDefaultInterface()
    .Configure(y => y.InRequestScope()));

IBindingRoot.Bind<IMessageRepository>().To<MessageRepository>)
    .WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey)
    .InRequestScope();

--> 您可以为每个存储库执行一个.Exclude&lt;TRepository&gt;(),其中约定绑定是不够的。对于每个排除的绑定,您必须自己指定一个。如上:所有实现IRepository&lt;&gt;的类的条件绑定exceptMessageRepository,它有自己的绑定。

也看看这个: 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()));

完全没问题。

【讨论】:

  • 感谢您的回复,我只是扩展我的问题,请您检查一下。
【解决方案2】:

如果您只有少数例外情况,则之前的解决方案有效。如果它们更多,您最终会遇到很多没有意义的约定。

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

IBindingRoot.Bind(x => x
.FromThisAssembly()
.SelectAllClasses()
.BindAllInterface());

IBindingRoot.Rebind<IMessageRepository>().To<MessageRepository>)
.WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey)
.InRequestScope();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多