使用Ninject批量注册通用接口的所有实现 [英] Batch registering all implementations of a generic interface with Ninject

查看:195
本文介绍了使用Ninject批量注册通用接口的所有实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have the following interfaces injected in Castle Windsor. how do i do the same in 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());

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

but getting Object reference not set to an instance of an object error.

推荐答案

您可以使用Ninject的常规绑定扩展程序(可从 NuGet 安装)进行此操作.

You can use Ninject's convention binding extensons (install it from NuGet) to do this.

类似以下的方法应该起作用

Something like the following should work

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

我不确定100%知道FromAssembliesMatching模式,但是您应该可以对其进行调整以拾取您的程序集.

I'm not 100% sure about the FromAssembliesMatching pattern, but you should be able to tweak that to pick up your assembly.

这篇关于使用Ninject批量注册通用接口的所有实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆