2

我在 NinjectModule 中有一些代码,它为多个程序集中的所有接口设置 Mock 绑定。Ninject 2 允许我在lambda中From()多次调用这些方法:Scan

Kernel.Scan(scanner =>
{
    string first = "MyAssembly";
    Assembly second = Assembly.Load("MyAssembly");
    scanner.From(first);
    scanner.From(second);
    scanner.BindWith<MockBindingGenerator>();
});

From()据我所知,Ninject 3 中的新方法不允许链式调用。这是我能想到的最好的等价物:

string first = "MyAssembly";
Assembly second = Assembly.Load("MyAssembly");

Kernel.Bind(x => x
    .From(first)
    .SelectAllInterfaces()
    .BindWith<MockBindingGenerator>());

Kernel.Bind(x => x
    .From(second)
    .SelectAllInterfaces()
    .BindWith<MockBindingGenerator>());

如上所示,当多次加载单个程序集时,我的新代码会中断*。注意firstsecond变量是不同类型的,所以我不能简单地将它们组合成一个调用。我的实际生产代码也有同样的问题,但我当然不是简单地对相同的程序集名称进行两次硬编码。

那么,我该如何重写上面的内容,以便我可以组合多个From()调用并且只调用BindWith<>一次呢?

编辑

* 绑定代码本身执行得很好。当我尝试获取绑定两次的程序集中存在的接口实例时,会发生异常。

4

2 回答 2

3

你看到https://github.com/ninject/ninject.extensions.conventions/wiki/OverviewJoin底部的语法了吗?我想这就是你所追求的...

(对于奖励积分:如果您看到文档并且它没有跳出来,您能否建议您是否认为最好将其分离到一个新的 Wiki 页面或您有其他想法?如果您只是在消费它来自 IntelliSense,您能建议一种您可能更容易发现它的方法吗?

编辑:经过反思,我猜你没有看到它,因为在.Join你完成这.Select...一点之前它不会变得可用。(顺便说一句,我对此感兴趣是因为我在 wiki 中进行了一些编辑;也可以随意编辑您从这次遭遇中学到的任何内容。))

于 2012-03-28T20:11:07.660 回答
2

我通过创建所有程序集名称的列表解决了我的问题:

string first = "MyAssembly";                    // .From("MyAssembly")
Assembly second = Assembly.Load("MyAssembly");  // .From(Assembly.Load("MyAssembly"))
Type third = typeof(Foo);                       // .FromAssemblyContaining<Foo>

Kernel.Bind(x => x
    .From(new [] { first, second.FullName, third.Assembly.FullName })
    .SelectAllInterfaces()
    .BindWith<MockBindingGenerator>());
于 2012-03-28T18:41:28.167 回答