gpt4 book ai didi

c# - Ninject 基于约定的绑定(bind) + 装饰器

转载 作者:行者123 更新时间:2023-11-30 12:10:55 25 4
gpt4 key购买 nike

我们正在使用基于 Ninjects 约定的绑定(bind)来自动将一组命令和查询绑定(bind)到它们的处理程序。到目前为止,我们有一个装饰器使用以下方法工作。

绑定(bind)所有没有属性的:

    Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithoutAttribute<DoCheckAttribute>()
.BindAllInterfaces());

用属性绑定(bind)所有:

    Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithAttribute<DoCheckAttribute>()
.BindAllInterfaces()
.Configure(c => c.WhenInjectedInto(typeof(DoCheckDecorator<>))));

我们尝试了以下方法来添加另一个装饰器,但是失败了。

绑定(bind)所有没有属性的:

    Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.WithoutAttribute<DoCheckAttribute>()
.WithoutAttribute<DoOtherCheckAttribute>()
.BindAllInterfaces());

用属性绑定(bind)所有:

    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),即?

    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();
}
}

这意味着绑定(bind)变得如此简单:

    Kernel.Bind(x =>
x.FromThisAssembly()
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.BindAllInterfaces());

现在可以轻松添加新属性,而无需对绑定(bind)进行任何更改。多个属性也可以定义它们运行的​​顺序,例如:

     [DoCheck(Order = 0), DoOtherCheck(Order = 1)]
public class TestClass
{
}

关于c# - Ninject 基于约定的绑定(bind) + 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16829978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com