我正在使用 Unity 进行依赖注入。我希望能够将我的记录器注入到所有依赖它的类中。我的问题是他们的记录器有一个构造函数参数,它需要Type
引用它的对象。如果我使用 Ninject,我会使用Logging 扩展。我如何在 Unity 中做同样的事情?
这是一些示例代码,可以准确显示我的意思。
public class Service1:IService1
{
private ILog _log;
public Service1(ILog log)
{
_log = log;
}
public void DoSomething()
{
_log.Print();
}
}
public class Service2:IService2
{
private ILog _log;
public Service2(ILog log)
{
_log = log;
}
public void DoSomething()
{
_log.Print();
}
}
public class Log:ILog
{
private Type _ownerType;
public Log(Type ownerType)
{
_ownerType = ownerType;
}
public void Print()
{
Console.Writeline("Owner: {0}", _ownerType.Name);
}
}
unityContainer.RegisterType<IService1, Service1>();
unityContainer.RegisterType<IService2, Service2>();
unityContainer.RegisterType<ILog, Log>() // This is wrong
var s1 = unityContainer.Resolve<IService1>();
var s2 = unityContainer.Resolve<IService2>();
s1.DoSomething(); // Should print "Owner: Service1"
s2.DoSomething(); // Should print "Owner: Service2"