如何实现代表工厂? [英] How do I implement a delegate factory?

查看:85
本文介绍了如何实现代表工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Autofac 的文档中有一个有趣的页面,描述了其自动生成委托工厂.它还强烈建议您通过手工编写,无需Autofac即可获得类似的结果.

The documentation for Autofac has an interesting page describing its ability to automatically generate delegate factories. It also strongly suggests that you can get similar results without Autofac by writing them by hand.

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

I'm using Unity for IoC and would like to avoid passing the container around to objects that need to create other objects, so how would you write a delegate factory without Autofac?

推荐答案

好吧,到目前为止我还没有使用过Unity,所以我的回答很模糊.

Well I've never used Unity so far, so my answer is quite vague.

原理很简单.您定义一些代表工厂的代表.然后,创建一个工厂"类,该类具有与委托匹配的公共方法.此类知道容器.现在,您注册委托并将该类设置为实现.然后,您只能注入委托.调用注入的委托时,将调用工厂类,该类知道容器并向容器询问新实例.

The principal is simple. You define some delegates which represent factories. Then you create a ‘factory’-class which has public methods which matches the delegates. This class knows the container. Now you register the delegate and set that class as implementation. Then you can inject only the delegate. When you call the injected delegate, the factory-class is called, which knows the container and asks the container for a new instance.

首先,您要定义工厂代表.

First you define your factory-delegates.

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

现在您注册代表的内容,是这样的:

Now what you register the delegate, something like this:

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

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

现在,您仅将提供程序"而不是容器注入其他组件.

Now other you inject to other components just the ‘Provider’ instead of the container.

这篇关于如何实现代表工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆