具有多个From的Ninject约定

时间:2012-03-28 17:24:23

标签: ninject ninject-3

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

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

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

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<>一次?

修改

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

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分: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>());