【问题标题】:Customizable Behavior using Unity Interception c#使用 Unity 拦截 c# 的可定制行为
【发布时间】:2021-08-12 22:19:51
【问题描述】:

我尝试为特定场景创建单独的可自定义拦截行为,例如 跟踪日志记录、异常日志记录、性能日志记录以及上述的组合。

但是,当我使用方法作为属性创建自定义行为时

[AttributeUsage(AttributeTargets.Method)]
public class LoggingBehaviorAttribute : Attribute , IInterceptionBehavior 
{
   public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
    {
        Console.WriteLine("Tracing.....");
        string ClassMethodName =
            string.Format("{0}::{1}", input.MethodBase.ReflectedType.Name, input.MethodBase.Name);

        //Logger
        log.Addlog(string.Format("Before {0} method execution ", ClassMethodName));
        log.Addlog("The Parameter Passed : " + GetParameterInfo(input));
        
        Console.WriteLine(string.Format("Before {0} method execution ", ClassMethodName));
        Console.WriteLine("The Parameter Passed : " + GetParameterInfo(input));

        IMethodReturn msg;

        try
        {

            Stopwatch Timer = new Stopwatch();

            //Start the Timer to capture the performance of the Method .
            Timer.Start();

            //Execute the Method after logging 
            msg = getNext()(input, getNext);
            
            //stop the timer
            Timer.Stop();

            Console.WriteLine("The Performance metric for the Method {0} is {1} ", 
            ClassMethodName,
                Timer.ElapsedMilliseconds);
}

在我的课堂上,我已经提到了需要拦截的方法的行为。

Public class Calculator : Icalculator 
{
    [LoggingBehavior]
    public float Add(float x, float y)
    {
        return x + y;
    }

    public float Subtract(float x, float y)
    {
        return x - y;
    }
}

在 My Main 类中,Interception 应用于两个类方法,而不是 Add() 方法之一。

主类代码:-

public static main()
{
     var container = new UnityContainer();

     container.AddNewExtension<Interception>();

     container.RegisterType<Icalculator, Calculator>(new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<LoggingBehaviorAttribute>());

     var Calc = container.Resolve<Icalculator>();

     //Performing Addition
     float result = Calc.Add(123, 343);

     //Performing Subraction
     float result1 = Calc.Subtract(123, 343);
}

有人可以指出我在定制方面犯了什么错误。容器注册有问题吗? 请补充您的想法....

【问题讨论】:

    标签: c# unity-container aop interception unity-interception


    【解决方案1】:

    这样试试

    public static main()
    {
         var container = new UnityContainer();
    
         container.RegisterType<Icalculator, Calculator>();
    
         var Calc = container.Resolve<Icalculator>();
    
         //Performing Addition
         float result = Calc.Add(123, 343);
    
         //Performing Subraction
         float result1 = Calc.Subtract(123, 343);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      相关资源
      最近更新 更多