将依赖对象的类型以统一方式传递给依赖项

时间:2013-08-15 21:38:23

标签: c# dependency-injection unity-container

我正在使用Unity进行依赖注入。我希望能够将我的记录器注入所有依赖它的类。我的问题是他们的logger有一个构造函数参数,需要引用它的对象的Type。如果我使用的是Ninject,我会使用Logging extension。我将如何在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"

2 个答案:

答案 0 :(得分:0)

思考可以帮助你,但我没有使用过Unity,所以..

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

希望,它会对你有帮助。

答案 1 :(得分: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"