相关疑难解决方法(0)

在Ninject中注入接口数组

请考虑以下代码.

public interface IFoo { }


public class Bar
{
    public Bar(IFoo[] foos) { }
}


public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<IFoo[]>().ToConstant(new IFoo[0]);
        // ToConstant() is just an example
    }
}


public class Program
{
    private static void Main(string[] args)
    {
        var kernel = new StandardKernel(new MyModule());
        var bar = kernel.Get<Bar>();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行该程序时,我得到以下异常.

激活IFoo时出错
没有匹配的绑定可用,并且该类型不可自我绑定.
激活路径:
2)将依赖关系IFoo注入到Bar
1 类型的构造函数的参数foo中.请求Bar

如何在Ninject中注入/绑定到数组?

谢谢你的时间.

编辑:
我的应用程序导入由第三方组件创建的数据.导入过程应用不同类型的过滤器(例如,不同过滤器接口的实现).过滤规则经常发生变化,但过于复杂,无法使用纯配置(和主过滤器).

我想尽可能简单地添加/编辑过滤器.我所拥有的是一个所有过滤器实现所在的程序集.我尝试将每个过滤器接口绑定到以下方法(它提供该过滤器类型的每个实现的实例).基本上我想避免在添加/删除过滤器类时更改我的Ninject模块.

    private IEnumerable<TInterface> GetInterfaceImplementations<TInterface>(IContext context)
    {
        return GetType().Assembly.GetTypes()
            .Where(t => …
Run Code Online (Sandbox Code Playgroud)

.net c# arrays dependency-injection ninject

14
推荐指数
2
解决办法
6012
查看次数

标签 统计

.net ×1

arrays ×1

c# ×1

dependency-injection ×1

ninject ×1