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

问题描述 投票:2回答:2

i在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());

但是获取对象引用未设置为对象错误的实例。

.net ninject ioc-container ninject.web.mvc
2个回答
7
投票

您可以使用Ninject的convention binding extensons(从NuGet安装)。

类似下面的东西应该起作用

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

我对FromAssembliesMatching模式不是100%的确定,但是您应该可以对其进行调整以选择您的程序集。


0
投票

我没有添加评论的声誉,所以我在这里写下。在ninject 4.0中,此方法将不起作用,因为它不包含Ninject.Modules.AssemlbyNameRetriever。因此,安装ninject 3.x版本。我也想知道什么是在ninject 4中做同样事情的正确版本。

© www.soinside.com 2019 - 2024. All rights reserved.