c# - 在接口(interface)上拦截

标签 c# ninject interceptor convention ninject-interception

我正在尝试制作类似 IAuditable 的东西接口(interface),作为 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>();我收到一个异常,告诉我有多个绑定(bind)可用。

如果我删除 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>()));

这会导致与使用接口(interface)相同的重复绑定(bind)问题。

最佳答案

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

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

关于c# - 在接口(interface)上拦截,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45508338/

相关文章:

android - Flutter webview 拦截所有请求并添加 headers

c# - System.Windows.Control.RichTextBox 中的错误

c# - 使用 Shdocvw 访问 Internet Explorer 会导致 UnauthorizedAccessException

c# - 这是引入 IEquatable<T> 的原因吗?

performance - ASP.NET MVC 3站点加载非常慢

java - CDI 项目中的 @AroundInvoke

c# - 你可以将 'expanded' 数组传递给 C# 中的函数,就像在 ruby​​ 中一样吗?

c# - Bootstrapper DisplayRootFor <MV>()异常: No parameterless constructor

.net - 按实现类型查找 Ninject 绑定(bind)

jquery - Ajax jquery 和 struts2 拦截器的参数