使用Ninject批量注册通用接口的所有实现

时间:2013-06-03 12:17:41

标签: .net ninject ioc-container ninject.web.mvc

我在Castle Windsor注入了以下接口。我如何在Ninject中做同样的事情?

container.Register(
    AllTypes.FromAssemblyNamed("Apps.Web")
        .BasedOn(typeof(ICommandHandler<>))
        .WithService.FirstInterface());

我试过了:

this.Bind(x => x.FromAssembliesMatching("Apps.Web.dll")
     .Select(y => y.Namespace.EndsWith("Handlers"))
     .BindSingleInterface());

但是没有将Object引用设置为对象错误的实例。

1 个答案:

答案 0 :(得分:7)

您可以使用Ninject的convention binding extensons(从NuGet安装)来执行此操作。

以下内容应该有效

kernel.Bind(x => x.FromAssembliesMatching("Apps.Web")
    .SelectAllClasses()
    .InheritedFrom(typeof(ICommandHandler<>))
    .BindSingleInterface());

我对FromAssembliesMatching模式并不是100%肯定,但你应该能够调整它以获取你的装配。

相关问题