如何在Ninject中修饰实现特定接口的所有绑定

Kev*_*ter 5 ninject mediatr

我正在使用Jimmy Bogard的Mediatr并试图在这里使用pipleine示例

我的问题是虽然我可以得到所有关闭的泛型类型

     kernel.Bind(
            x =>
                x.FromAssemblyContaining<ExpensiveRequest>()
                    .SelectAllClasses()
                    .InheritedFrom(typeof (IRequestHandler<,>)).BindAllInterfaces()
Run Code Online (Sandbox Code Playgroud)

我不能用MediatorPipeline来装饰它们.

所以,如果我使用StructureMap,我可以使用这样的东西

cfg.For(typeof(IRequestHandler<,>)).DecorateAllWith(typeof(MediatorPipeline<,>));
Run Code Online (Sandbox Code Playgroud)

我无法找到如何使用Ninject实现它,以便在调用我的Mediator时它使用Mediator管道,然后使用原始的Handler

Aar*_*nHS 2

有几种方法可以做到这一点。您可以执行您已经在执行的基于约定的扫描,然后在其末尾添加上下文绑定:

kernel.Bind(x => x.FromAssemblyContaining<ExpensiveRequest>()
     .SelectAllClasses()
     .InheritedFrom(typeof(IRequestHandler<,>))
     .BindAllInterfaces();
     .Configure(c => c.WhenInjectedExactlyInto(typeof(MediatorPipeline<,>));
Run Code Online (Sandbox Code Playgroud)

然后在没有上下文过滤器的情况下再次执行完全相同的操作WhenInjectedExactlyInto

kernel.Bind(x => x.FromAssemblyContaining<ExpensiveRequest>()
     .SelectAllClasses()
     .InheritedFrom(typeof(IRequestHandler<,>))
     .BindAllInterfaces();
Run Code Online (Sandbox Code Playgroud)

但这需要进行两次程序集扫描。

另一种方法是编写一个 IBindingGenerator,并在其中执行多个绑定 - 一个有WhenInjectedExactlyInto,另一个没有。.BindWith<MyBindingGenerator>()然后,这将只需要使用语法而不是基于单个约定的绑定.BindAllInterfaces()