拦截接口

时间:2017-08-04 13:37:49

标签: c# ninject interceptor convention ninject-interception

我正在尝试创建类似IAuditable接口的东西,它充当Ninject拦截调用的标记。

假设我有以下内容:

public interface IAuditable
{

}

public interface IProcessor
{
    void Process(object o);
}

public class Processor : IProcessor, IAuditable
{
    public void Process(object o)
    {
        Console.WriteLine("Processor called with argument " + o.ToString());
    }
}

使用此设置:

NinjectSettings settings = new NinjectSettings() { LoadExtensions = true };
IKernel kernel = new StandardKernel(settings);
kernel.Bind<IAuditAggregator>().To<AuditAggregator>().InThreadScope();
kernel.Bind<IAuditInterceptor>().To<AuditInterceptor>();

kernel.Bind(x =>
            x.FromThisAssembly()
            .SelectAllClasses()
            .InheritedFrom<IAuditable>()
            .BindToDefaultInterfaces() //I suspect I need something else here
            .Configure(c => c.Intercept().With<IAuditInterceptor>()));
kernel.Bind<IProcessor>().To<Processor>();

每当我尝试kernel.Get<IProcessor>();时,我都会收到异常,告诉我有多个绑定可用。

如果我删除了kernel.Bind<IProcessor>().To<Processor>(),那么它会按预期工作,但您可能有一个IProcessor没有实现IAuditable

我是在正确的轨道上吗?

编辑:根据建议,我尝试使用属性:

public class AuditableAttribute : Attribute
{

}
[Auditable]
public class Processor : IProcessor
{

    public void Process(object o)
    {
        Console.WriteLine("Processor called with argument " + o.ToString());
    }
}
//in setup:
kernel.Bind(x =>
            x.FromThisAssembly()
            .SelectAllClasses()
            .WithAttribute<AuditableAttribute>()
            .BindDefaultInterface()
            .Configure(c => c.Intercept().With<IAuditInterceptor>()));

这导致与使用接口相同的重复绑定问题。

1 个答案:

答案 0 :(得分:1)

您应该能够为实现IAuditable的类型编写一个约定绑定,为未实现的类型编写一个约定。

        kernel.Bind(x =>
            x.FromThisAssembly()
                .SelectAllClasses()
                .InheritedFrom<IAuditable>()
                .BindDefaultInterfaces()
                .Configure(c => c.Intercept().With<IAuditInterceptor>()));

        kernel.Bind(x =>
            x.FromThisAssembly()
                .SelectAllClasses()
                .InheritedFrom<IProcessor>()
                .Where(t => !typeof(IAuditable).IsAssignableFrom(t))
                .BindDefaultInterfaces());