使用 Unity 拦截 c# 的可自定义行为

Customizable Behavior using Unity Interception c#

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

但是,当我创建一个以方法作为属性的自定义行为时

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

在我的 Class 中,我提到了需要拦截的方法的行为。

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 class 中,拦截应用于两个 class 方法,而不是一个 Add() 方法。

主要Class代码:-

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

谁能指出我在定制中哪里出错了。容器注册有问题吗? 请补充您的想法....

这样试试

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