嗯,到目前为止我还没有使用过统一,所以我的回答很含糊。
校长很简单。定义一些代表工厂的代理。然后创建一个__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);
现在,其他组件只注入__provider_,而不是容器。