我们使用基于 Ninjects 约定的绑定来自动将一组命令和查询绑定到它们的处理程序。到目前为止,我们有一个装饰器使用以下内容工作。
绑定所有没有属性:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithoutAttribute<DoCheckAttribute>()
.BindAllInterfaces());
使用属性绑定所有:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithAttribute<DoCheckAttribute>()
.BindAllInterfaces()
.Configure(c => c.WhenInjectedInto(typeof(DoCheckDecorator<>))));
我们尝试了以下方法来添加另一个装饰器,但是失败了。
绑定所有没有属性:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithoutAttribute<DoCheckAttribute>()
.WithoutAttribute<DoOtherCheckAttribute>()
.BindAllInterfaces());
使用属性绑定所有:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithAttribute<DoCheckAttribute>()
.WithoutAttribute<DoOtherCheckAttribute>()
.BindAllInterfaces()
.Configure(c => c.WhenInjectedInto(typeof(DoCheckDecorator<>))));
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithoutAttribute<DoCheckAttribute>()
.WithAttribute<DoOtherCheckAttribute>()
.BindAllInterfaces()
.Configure(c => c.WhenInjectedInto(typeof(DoOtherCheckDecorator<>))));
是否可以使用 Ninject 以这种方式实现这一目标?我们是否必须回滚到手动定义每个绑定,即?
Bind<X>.To<Y>.WhenInjectedInto(?)
理想情况下,我们会使用如下语法:
Bind<X>.To<Y>.WithDecorator<Z>.When(a => a.HasAttribute<DoCheckAttribute>)