简体   繁体   English

城堡拦截器不拦截

[英]Castle Interceptor not Intercepting

I have a lot of code I want to add logging to. 我有很多代码想要添加日志记录。 My plan was to use Unity or Castle.Windsor to create an intercepted logging routine, and to add it to existing code by using a custom C# attribute. 我的计划是使用Unity或Castle.Windsor创建一个拦截的日志记录例程,并通过使用自定义C#属性将其添加到现有代码中。 I cannot change the existing code structure (but I can add startup configuration to it, so the container registration approach is OK). 我无法更改现有的代码结构(但是可以向其添加启动配置,因此容器注册方法是可以的)。

This didn't look possible with Unity without changing the call structure (getting the intercepted class required changing the instantiation to use registered dependency injection), so I'm trying Castle.Windsor. 在没有更改调用结构的情况下,Unity似乎无法实现(获取被拦截的类需要更改实例化以使用注册的依赖项注入),因此我正在尝试Castle.Windsor。 This code I have is not firing the Intercept routine. 我的这段代码没有触发Intercept例程。

This gave me some hope that it will be possible in Castle.Windsor: Inject logging dependency with Castle Windsor 这给了我一些希望,在Castle.Windsor中成为可能: 使用Castle Windsor注入日志记录依赖项

using System;
using Castle.Core;
using Castle.DynamicProxy;
using Castle.MicroKernel.Registration;
using Castle.Windsor;

namespace UnityTestProject
{
    class Program
    {
        private static WindsorContainer container;

        static void Main(string[] args)
        {
            container = new WindsorContainer();
            container.Register(Component.For<MyLogger>().LifeStyle.Transient);

            ICalcService c = new Calc();
            Console.WriteLine(c.Add(3,4));
            Console.ReadKey();
        }
    }

    public class MyLogger : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            Console.WriteLine("Inovaction called!");
            invocation.Proceed();
        }
    }

    public interface ICalcService
    {
        int Add(int x, int y);
    }

    public class Calc : ICalcService
    {
        [Interceptor(typeof(MyLogger))]
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}

Is there a better way for me to do this logging injection? 我是否有更好的方法进行此日志记录注入? PostSharp weaving would be ideal, but I cannot use it (expense and licensing). PostSharp编织将是理想的,但是我不能使用它(费用和许可)。

changed main to : 将main更改为:

container = new WindsorContainer();
container.Register(
    Component.For<ICalcService>().ImplementedBy<Calc>().Interceptors<MyLogger>(),
    Component.For<MyLogger>().LifeStyle.Transient);

ICalcService c = container.Resolve<ICalcService>();
Console.WriteLine(c.Add(3, 4));
Console.ReadKey();

And you can remove the interceptor attribute. 并且您可以删除拦截器属性。 If you want to do interception with windsor then Windsor must be allowed to created the component(s). 如果要使用windsor进行拦截,则必须允许Windsor创建组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM