6

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

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

4

1 回答 1

6

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

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

首先你定义你的工厂委托。

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);

现在你注入其他组件只是“提供者”而不是容器。

于 2009-11-21T14:25:15.567 回答