1

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

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

[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() Method 之一。

主类代码:-

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

有人可以指出我在定制中犯错的地方吗?容器注册有问题吗?请补充您的想法....

4

1 回答 1

0

试试这样

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);
}
于 2021-08-12T14:19:51.467 回答