使用自定义属性的.NET Unity拦截

问题描述 投票:3回答:2

我想得到答案here中描述的行为,但通过代码使用配置。代码示例显示创建的自定义属性没有任何统一相关,并通过配置添加行为。

自定义属性位于同一解决方案中引用的单独程序集中。

问题是它在配置期间抛出异常:

InvalidOperationException:类型Microsoft.Practices.Unity.InterceptionExtension.CustomAttributeMatchingRule没有带参数的构造函数(LogAttribute,Boolean)。

container
    .AddNewExtension<Interception>()
    .Configure<Interception>()
        .AddPolicy("MyLoggingPolicy")
        .AddMatchingRule<CustomAttributeMatchingRule>(
        new InjectionConstructor(typeof(Abstractions.Attributes.LogAttribute), true))
        .AddCallHandler<LoggingHandler>(new ContainerControlledLifetimeManager())
            .Interception
            .Container
        .RegisterType<IFirstInterface>(new InjectionFactory((context) => FirstClassFactoryMethod()))
        .RegisterType<ISecondInterface>(new InjectionFactory((context) => SecondClassFactoryMethod()));

[AttributeUsage(AttributeTargets.Method)]
public class LogAttribute : Attribute { }

public class LoggingHandler : ICallHandler
{
    public int Order { get; set; }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} Started: {input.MethodBase.Name}");
        var result = getNext()(input, getNext);
        Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")} Completed: {input.MethodBase.Name}");
        return result;
    }
}

更新引发的行:

.AddMatchingRule(
    new CustomAttributeMatchingRule(typeof(Abstractions.Attributes.LogAttribute), true))

防止抛出异常,但LoggingHandler不接收来自具有[Log]属性的方法的任何调用。

注意:标记为[Log]的方法是公共方法,在不同的程序集中,在使用.Resolve()实例化的类中。

c# unity-container aop unity-interception
2个回答
4
投票

对于遇到相同问题的任何人 - 我必须在已注册的类型上定义拦截行为:

.RegisterType<IFirstInterface>(
    new InjectionFactory((context) => FirstClassFactoryMethod())
    new Interceptor<TransparentProxyInterceptor>()
    new InterceptionBehavior<PolicyInjectionBehavior>())
.RegisterType<ISecondInterface>(
    new InjectionFactory((context) => SecondClassFactoryMethod())
    new Interceptor<TransparentProxyInterceptor>()
    new InterceptionBehavior<PolicyInjectionBehavior>()));

0
投票

我得到了相同的错误并尝试了Filip解决方案,但没有奏效。对我来说,改变了InjectionCactory的InjectionConstructor(Unity 4.0.1):

container
.AddNewExtension<Interception>()
.Configure<Interception>()
    .AddPolicy("MyLoggingPolicy")
    .AddMatchingRule<CustomAttributeMatchingRule>(
    new InjectionFactory((context) => new CustomAttributeMatchingRule(typeof(Abstractions.Attributes.LogAttribute), true))
    .AddCallHandler<LoggingHandler>(new ContainerControlledLifetimeManager());

希望这有助于某人。

© www.soinside.com 2019 - 2024. All rights reserved.