Unity 支持自动连接,它允许您解析复杂的对象图,而不仅仅是单个对象。
例如,假设您有一个类Car 实现ICar,它依赖于另一个类IEngine,使用构造函数注入(汽车的构造函数需要一个IEngine 类型的参数)。
public interface ICar
{
void Accelerate();
}
public interface IEngine
{
void Accelerate();
}
public class Car: ICar
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine;
}
public void Accelerate()
{
_engine.Accelerate();
}
}
public class Engine: IEngine
{
public Engine()
{
}
public string Message {get; set;}
public void Accelerate()
{
Console.WriteLine("Accelerating." + Message);
}
}
然后您将在 Unity 中注册如何解析 ICar 和 IEngine:
var _container = new UnityContainer()
.RegisterType<ICar,Car>()
.RegisterType<IEngine,Engine>(
new InjectionProperty("Message", "Hello world"));
然后,当您解析ICar 时,Unity 将能够向Car 构造函数提供Engine 的实例,自动连接 Car 对 IEngine 的依赖项。对于 Car 或 Engine 可能具有的任何其他依赖项以及为注入注册的任何属性也是如此。
var car = _container.Resolve<Car>();
car.Accelerate();
加速。你好世界
这种方式通过解析ICar Unity 将为您提供所需的完整对象图。你可以试试样品in this fiddle
编辑
您可以使用将在运行时执行的 lambda 方法注册要解析的类型,例如:
public interface IFoo
{
DateTime ResolvedTime {get; set;}
}
public class Foo: IFoo
{
public DateTime ResolvedTime {get; set;}
}
//Can be registered using a lambda as in:
container.RegisterType<IFoo,Foo>(
new InjectionFactory(c => new Foo{ ResolvedTime = DateTime.Now }));
你可以得到一些信息on the msdn。我还用这个 lambda 示例更新了上面的小提琴。