首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Unity Interception c#可自定义行为

使用Unity Interception c#可自定义行为
EN

Stack Overflow用户
提问于 2021-08-11 07:47:51
回答 1查看 48关注 0票数 1

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

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

代码语言:javascript
运行
复制
[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);
}

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

代码语言:javascript
运行
复制
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()方法。

主类代码:-

代码语言:javascript
运行
复制
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);
}

有没有人能指出我在定制方面犯了什么错误?容器注册有问题吗?请补充你的想法……

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-12 14:19:51

试着这样做

代码语言:javascript
运行
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68738003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档