c# – 基于Ninject约定的绑定装饰器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 基于Ninject约定的绑定装饰器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2341字,纯文字阅读大概需要4分钟。
内容图文
![c# – 基于Ninject约定的绑定装饰器](/upload/InfoBanner/zyjiaocheng/785/1678359e026245b9b4afeb2cb1a71842.jpg)
我们使用基于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>)
解决方法:
所以似乎Ninject已经有了一个可以解决这个问题的扩展.使用拦截器扩展可以将属性写为:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class DoCheckAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Context.Kernel.Get<DoCheckInterceptor>();
}
}
然后将实际拦截写为:
public class DoCheckInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
//Do Work
invocation.Proceed();
}
}
这意味着绑定变得如此简单:
Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.BindAllInterfaces());
现在可以轻松添加新属性,而无需对绑定进行任何更改.多个属性也可以具有定义的运行顺序,例如:
[DoCheck(Order = 0), DoOtherCheck(Order = 1)]
public class TestClass
{
}
内容总结
以上是互联网集市为您收集整理的c# – 基于Ninject约定的绑定装饰器全部内容,希望文章能够帮你解决c# – 基于Ninject约定的绑定装饰器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。