0

我正在使用 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"
4

2 回答 2

0

您可以将记录器注册为开放泛型类型,然后在每个服务中解析解析记录器的类的封闭泛型。

public class Service1:IService1
{
    private ILog _log;
    public Service1(ILog<Service1> log)
    {
        _log = log;
    }

    public void DoSomething()
    {
        _log.Print();
    }
}

public class Service2:IService2
{
    private ILog _log;
    public Service2(ILog<Service2> log)
    {
        _log = log;
    }

    public void DoSomething()
    {
        _log.Print();
    }
}

public interface ILog
{
    void Print();
}

public interface ILog<T> : ILog 
{
    //Any type specific methods
}

public class Log<T> : ILog<T>
{
    public void Print()
    {
        Console.Writeline("Owner:  {0}", typeof(T).Name);
    }
}

unityContainer.RegisterType<IService1, Service1>();
unityContainer.RegisterType<IService2, Service2>();
unityContainer.RegisterType(typeof(ILog<>), typeof(Log<>))

var s1 = unityContainer.Resolve<IService1>();
var s2 = unityContainer.Resolve<IService2>();

s1.DoSomething(); // Should print "Owner:  Service1"
s2.DoSomething(); // Should print "Owner:  Service2"
于 2013-08-30T06:01:32.410 回答
0

Think in 可以帮到你,但是我没用过Unity,所以..

http://davidkeaveny.blogspot.ru/2011/03/unity-and-log4net.html

希望,它会帮助你。

于 2013-08-16T04:21:00.380 回答