Unity 文档指出:
如果开发人员使用 Unity 容器的 Resolve 方法实例化的类具有定义对其他类的一个或多个依赖项的构造函数,则 Unity 容器会自动创建在构造函数的参数中指定的依赖对象实例
这很好,但大多数情况下我不指定注入类,而是指定接口,以保持事物解耦。
那么,当我 .Resolve<>指定接口注入而不是类注入的类时,如何利用 Unity 的自动注入?
即在下面的代码中,当我将我的客户构造函数更改为“ public Customer(ILogger logger) ”时,如何使它工作?
using System;
using Microsoft.Practices.Unity;
namespace TestUnityInjection23
{
public class Program
{
static void Main(string[] args)
{
Customer customer1 = new Customer(new BasicLogger());
//Customer customer2 = new Customer(new AdvancedLogger()); //can't use this since Customer only accepts BasicLogger
UnityContainer container = new UnityContainer();
container.RegisterType<Customer>();
container.RegisterType<ILogger, BasicLogger>();
Customer customer3 = container.Resolve<Customer>();
Console.ReadLine();
}
}
public class Customer
{
public Customer(BasicLogger logger) //would like to have Customer depend on ILogger here so logger can be swapped out
{
logger.WriteToLog("creating the customer");
}
}
public interface ILogger
{
void WriteToLog(string text);
}
public class BasicLogger : ILogger
{
public void WriteToLog(string text)
{
Console.WriteLine(text);
}
}
public class AdvancedLogger : ILogger
{
public void WriteToLog(string text)
{
Console.WriteLine("*** {0} ***", text);
}
}
}