【问题标题】:Castle Interceptor not Intercepting城堡拦截器不拦截
【发布时间】:2013-06-25 21:38:38
【问题描述】:

我有很多代码要添加日志记录。我的计划是使用 Unity 或 Castle.Windsor 创建截获的日志记录例程,并使用自定义 C# 属性将其添加到现有代码中。我无法更改现有的代码结构(但我可以为其添加启动配置,因此容器注册的方式是可以的)。

在不更改调用结构的情况下使用 Unity 似乎是不可能的(获取被拦截的类需要更改实例化以使用注册的依赖注入),所以我正在尝试 Castle.Windsor。我拥有的这段代码没有触发 Intercept 例程。

这给了我一些希望,在 Castle.Windsor 中它是可能的: Inject logging dependency with 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;
        }
    }
}

有没有更好的方法来进行这种日志注入? PostSharp 编织将是理想的,但我不能使用它(费用和许可)。

【问题讨论】:

  • 我阅读了您关于无法更改代码结构的限制,但对于长期代码改进,我认为您应该真正考虑围绕一些巧妙选择的通用接口设计您的应用程序。这使得添加横切关注点变得更加容易,例如稍后将日志记录到您的应用程序。例如查看thisthisthis 文章。

标签: c# castle-windsor unity-container unity-interception


【解决方案1】:

将主要更改为:

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

您可以删除拦截器属性。如果你想用 windsor 进行拦截,则必须允许 Windsor 创建组件。

【讨论】:

  • 是的,这个 'container.Resolve()' 是我希望不必做的,但从长远来看,我可以看到它更好。我只需要让我的团队的其他成员加入。不过,这对我来说现在看起来很像 Unity,语法几乎相同。 Unity和Windsor有很大区别吗?实际上,我找到了这个并回答了我的问题:stackoverflow.com/questions/2216684/…
猜你喜欢
  • 2015-06-21
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多