我有很多我想要添加日志记录的代码。我的计划是使用Unity或Castle.Windsor创建拦截日志记录例程,并使用自定义C#属性将其添加到现有代码中。我无法更改现有的代码结构(但我可以向其添加启动配置,因此容器注册方法可以)。城堡拦截器不拦截
这看起来不可能在不改变调用结构的情况下(让截获的类需要改变实例化来使用注册的依赖注入),所以我试着使用Castle.Windsor。这个代码我没有触发拦截例程。
这给了我一些希望,这将有可能在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编织将是理想的,但我不能使用它(费用和许可)。
我读到了关于无法更改代码结构的约束,但对于长期的代码改进,我认为您应该考虑围绕几个巧妙选择的通用接口设计您的应用程序。这使得添加横切关注点变得更加容易,例如稍后登录到应用程序。看看[this](http://bit.ly/s7tGEH),[this](http://bit.ly/s3UUyv)和[this](http://bit.ly/RrJRvD )文章。 – Steven