代码之家  ›  专栏  ›  技术社区  ›  GraemeF

如何实现代理工厂?

  •  6
  • GraemeF  · 技术社区  · 15 年前

    文件 Autofac 有一个有趣的页面描述它自动生成的能力 delegate factories . 它还强烈建议您可以在不使用autopac的情况下,通过手写来获得类似的结果。

    我正在为IOC使用Unity,希望避免将容器传递给需要创建其他对象的对象,那么,如果不使用autopac,如何编写代理工厂呢?

    1 回复  |  直到 15 年前
        1
  •  6
  •   Gamlor Gabriele Ran    15 年前

    嗯,到目前为止我还没有使用过统一,所以我的回答很含糊。

    校长很简单。定义一些代表工厂的代理。然后创建一个__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_,而不是容器。