我有很多代码想要添加日志。我的计划是使用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编织将是理想的,但我不能使用它(费用和许可)。
发布于 2013-06-28 15:46:47
将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();并且您可以删除拦截器属性。如果您想使用windsor进行拦截,则必须允许Windsor创建组件。
https://stackoverflow.com/questions/17359198
复制相似问题