代码之家  ›  专栏  ›  技术社区  ›  Filip

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

  •  3
  • Filip  · 技术社区  · 7 年前

    here 但是通过代码使用配置。代码示例显示创建的自定义属性没有任何与统一相关的内容,并通过配置添加行为。

    问题是它在配置期间引发异常:

    InvalidOperationException:类型Microsoft。实践。团结一致拦截扩展。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))
    

    2 回复  |  直到 7 年前
        1
  •  5
  •   Filip    7 年前

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

    .RegisterType<IFirstInterface>(
        new InjectionFactory((context) => FirstClassFactoryMethod())
        new Interceptor<TransparentProxyInterceptor>()
        new InterceptionBehavior<PolicyInjectionBehavior>())
    .RegisterType<ISecondInterface>(
        new InjectionFactory((context) => SecondClassFactoryMethod())
        new Interceptor<TransparentProxyInterceptor>()
        new InterceptionBehavior<PolicyInjectionBehavior>()));
    
        2
  •  0
  •   fuegonju    5 年前

    我也遇到了同样的错误,尝试了Filip解决方案,但没有成功。对于我来说,为InjectionFactory(Unity 4.0.1)更改InjectionConstructor:

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