我如何实现委托工厂?

Gra*_*meF 6 c# factory inversion-of-control unity-container autofac

Autofac的文档有一个有趣的页面,描述了它自动生成委托工厂的能力.它还强烈建议您在没有Autofac的情况下手动编写可以获得类似的结果.

我正在使用Unity for IoC并且希望避免将容器传递给需要创建其他对象的对象,那么如何在没有Autofac的情况下编写委托工厂?

Gam*_*lor 6

好吧我到目前为止从未使用过Unity,所以我的答案很模糊.

校长很简单.您定义了一些代表工厂的委托.然后创建一个'factory'类,它具有与委托匹配的公共方法.这个类知道容器.现在注册委托并将该类设置为实现.然后你只能注入委托.当您调用注入的委托时,将调用工厂类,它知道容器并向容器请求新实例.

首先,您定义工厂代表.

public delegate TServiceType Provider<TServiceType>();
public delegate TServiceType Provider<TArg,TServiceType>(TArg argument);
Run Code Online (Sandbox Code Playgroud)

你创建了一个通用工厂:

/// <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)});
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您注册了委托,如下所示:

var newServiceCreater = new GenericFactory(container);
container.Register<Provider<MyCompoent>>().To(newServiceCreater.Create);

var newServiceCreater = new GenericFactory(container);
container
    .Register<Provider<OtherServiceWithOneArgumentToConstruct>>()
    .To(newServiceCreater.Create);
Run Code Online (Sandbox Code Playgroud)

现在,您可以向其他组件注入"Provider"而不是容器.