Autofac的文档有一个有趣的页面,描述了它自动生成delegate factories的能力。它还强烈建议您在没有Autofac的情况下通过手工编写来获得类似的结果。
我正在使用Unity for IoC,并且希望避免将容器传递给需要创建其他对象的对象,那么如何在没有Autofac的情况下编写委托工厂?
答案 0 :(得分:6)
到目前为止我从未使用过Unity,所以我的回答很模糊。
校长很简单。您定义了一些代表工厂的委托。然后创建一个'factory'类,它具有与委托匹配的公共方法。这个类知道容器。现在注册委托并将该类设置为实现。然后你只能注入委托。当您调用注入的委托时,将调用工厂类,它知道容器并向容器请求新实例。
首先定义工厂代表。
public delegate TServiceType Provider<TServiceType>();
public delegate TServiceType Provider<TArg,TServiceType>(TArg argument);
您创建了一个通用工厂:
/// <summary>
/// Represents a <see cref="Provider{TArg,TServiceType}"/> which holds
/// the container context and resolves the service on the <see cref="Create"/>-call
/// </summary>
internal class GenericFactory{
private readonly IContainer container;
public ClosureActivator(IContainer container)
{
this.container= container;
}
/// <summary>
/// Represents <see cref="Provider{TServiceType}.Invoke"/>
/// </summary>
public TService Create()
{
return container.Resolve<TService>();
}
/// <summary>
/// Represents <see cref="Provider{TArg,TServiceType}.Invoke"/>
/// </summary>
public TService Create(TArg arg)
{
return container.Resolve<TService>(new[] {new TypedParameter(typeof (TArg),arg)});
}
}
现在注册委托的内容如下:
var newServiceCreater = new GenericFactory(container);
container.Register<Provider<MyCompoent>>().To(newServiceCreater.Create);
var newServiceCreater = new GenericFactory(container);
container
.Register<Provider<OtherServiceWithOneArgumentToConstruct>>()
.To(newServiceCreater.Create);
现在,您可以向其他组件注入“提供者”而不是容器。