通过城堡动态代理使用非空构造函数的Ninject拦截代理类

时间:2014-03-12 10:34:20

标签: ninject aop castle-dynamicproxy ninject-interception

我的大部分当前实现都是基于此处提供的信息:

Ninject Intercept any method with certain attribute?

我使用一个自定义计划策略类,它查找具有给定属性的所有方法(不是ninject拦截器属性),如果它符合条件,它们将被代理。

使用的一个例子是:

Kernel.Components.Add<IPlanningStrategy, CustomPlanningStrategy<LoggingAttribute, LoggerInterceptor>>();

然后,这会查找具有[Logging]属性的任何方法,然后使用日志记录拦截器。

但是,当我尝试使用相关属性代理方法时,我正在从动态代理获取InvalidProxyConstructorArgumentsException。现在我记得读过你需要虚拟方法,但是我不记得看到你有一个无参数的构造函数。

所有绑定都是针对接口完成的,AOP拦截器是通过属性和上面链接中提到的自定义代理规划类实现的。

那么有没有办法让动态代理(或linfu版本)代理具有依赖关系的构造函数的类? (所有依赖项都在内核中,因此它们不能解决它们。)

2 个答案:

答案 0 :(得分:4)

查看代理生成代码: https://github.com/ninject/ninject.extensions.interception/blob/master/src/Ninject.Extensions.Interception.DynamicProxy/DynamicProxyProxyFactory.cs

    if (targetType.IsInterface)
        {
            reference.Instance = this.generator.CreateInterfaceProxyWithoutTarget(targetType, additionalInterfaces, InterfaceProxyOptions, wrapper);
        }
        else
        {
            object[] parameters = context.Parameters.OfType<ConstructorArgument>()
                .Select(parameter => parameter.GetValue(context, null))
                .ToArray();
            reference.Instance = this.generator.CreateClassProxy(targetType, additionalInterfaces, ProxyOptions, parameters, wrapper);
        }

可以看到ninject的动态代理扩展仅将ConstructorArgument传递给Castle动态代理生成器。

所以 - 无需更改ninject扩展或创建自己的扩展 - 您需要将所有依赖项作为构造函数参数传递。您还可以尝试使用属性/方法注入(请参阅https://github.com/ninject/ninject/wiki/Injection-Patterns)。

如果您控制代码,则可以将接口添加到代理类,然后使用“interface proxy with target”。这允许将代理实例化与目标(代理类)实例化分离 - &gt; target可以在不对ninject(-extensions)进行任何更改的情况下注入依赖关系。

<强>澄清: 有以下应该代理的类:

public interface IBar { }

public class Foo 
{
     public Foo(IBar bar)
     {
     }
}

以下绑定:

Bind<Foo>().ToSelf().Intercept().With<SomeInterceptor>();
Bind<IBar>().To<Bar>();

然后从ninject容器中检索Foo

IResolutionRoot.Get<Foo>();

无效。

将所有构造函数参数放在ninject上下文中以使其正常工作

但是,我们可以更改Foo的检索以使其正常工作:

var bar = IResolutionRoot.Get<IBar>();
IResolutionRoot.Get<Foo>(new ConstructorArgument("bar", bar);

现在这不是最理想的,因为ninject没有自动执行依赖项解析。

向代理类添加接口以使其更好地工作

我们可以通过使用“带目标的接口代理”来解决此问题。 首先,我们为代理类添加一个接口:

public interface IFoo{ }

public class Foo : IFoo
{
     public Foo(IBar bar)
     {
     }
}

然后我们将绑定更改为:

Bind<IFoo>().To<Foo>().Intercept().With<SomeInterceptor>();

然后从ninject容器中检索Foo

IResolutionRoot.Get<Foo>();

作品。

另一种可能更简单(&amp; uglier?)的解决方案 根据@Daniel的说法: 将两个构造函数添加到代理类型:

  • 一个没有参数的protected构造函数。这个是为DynamicProxy创建代理。
  • 带有参数的public / internal构造函数,由ninject用于实例化代理类型。

Ninject将自动选择具有可以解析的最多参数的构造函数。

答案 1 :(得分:3)

另一种方法是使用具有[Logging]属性的方法对所有类使用基于约定的绑定。但是,这意味着向方法添加[Logging]属性将影响对象的绑定,这可能是不期望的。

这就是它如何工作(验证工作):

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class LoggingAttribute : Attribute
{
}

public interface IClassNotToBeIntercepted
{
    void DoSomething();
}

public class ClassNotToBeIntercepted : IClassNotToBeIntercepted
{
    public void DoSomething() { }
}

public interface IClassToBeIntercepted
{
    void DoNotLogThis();
    void LogThis();
    void LogThisAsWell();
}

public class ClassToBeIntercepted : IClassToBeIntercepted
{
    public void DoNotLogThis() { }

    [Logging]
    public void LogThis() { }

    [Logging]
    public void LogThisAsWell() { }
}

public class LoggingInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("interceptor before {0}", BuildLogName(invocation));

        invocation.Proceed();

        Console.WriteLine("interceptor after {0}", BuildLogName(invocation));
    }

    private static string BuildLogName(IInvocation invocation)
    {
        return string.Format(
            "{0}.{1}", 
            invocation.Request.Target.GetType().Name,
            invocation.Request.Method.Name);
    }
}

public class DemoModule : NinjectModule
{
    public override void Load()
    {
        this.Bind(convention => convention
            .FromThisAssembly()
            .SelectAllClasses()
            .Where(ContainsMethodWithLoggingAttribute)
            .BindDefaultInterface()
            .Configure(x => x
                .Intercept()
                .With<LoggingInterceptor>()));

        this.Bind<IClassNotToBeIntercepted>()
            .To<ClassNotToBeIntercepted>();
    }

    private static bool ContainsMethodWithLoggingAttribute(Type type)
    {
        return type
            .GetMethods()
            .Any(method => method.HasAttribute<LoggingAttribute>());
    }
}

测试:

    [Fact]
    public void InterceptorTest()
    {
        var kernel = new StandardKernel();
        kernel.Load<DemoModule>();

        kernel.Get<IClassNotToBeIntercepted>()
            .DoSomething();

        kernel.Get<IClassToBeIntercepted>()
            .LogThis();
    }

以下控制台输出结果:

interceptor before ClassToBeIntercepted.LogThis
interceptor after ClassToBeIntercepted.LogThis
相关问题