Настраиваемое поведение с использованием перехвата Unity c#

#c# #unity-container #aop #interception #unity-interception

Вопрос:

Я пытаюсь создать отдельное настраиваемое поведение перехвата для конкретных сценариев, таких как ведение журнала трассировки, ведение журнала исключений , ведение журнала производительности и их сочетание.

Однако , когда я создал пользовательское поведение с методом в качестве атрибута

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

В моем основном классе Перехват применяется к обоим методам класса вместо одного метода 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);
}
 

Может ли кто-нибудь указать мне, где я допускаю ошибку в настройке . Что-то не так с регистрацией контейнера ?
Пожалуйста, добавьте свои мысли ….

Ответ №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);
}