使用SingleInstance基于参数委派工厂

时间:2016-06-16 21:02:40

标签: c# autofac

我有一个接口和一个类,我想为它创建实例:

public interface IFoo
{
    void Frob();
}

public class Foo : IFoo
{
    public Foo(string key)
    {
    }
}

Foo类有一个string key参数,在运行时不会知道。我为此创建了一个委托工厂:

public delegate IFoo FooFactory(string key);

我想注册Foo以便它具有SingleInstance范围,但我希望它是基于关键参数的SingleInstance。

var foo1 = fooFactory("abc");  // new instance
var foo2 = fooFactory("abc");  // same instance as foo2
var foo3 = fooFactory("def");  // new instance
var foo4 = fooFactory("def");  // same instance as foo4

我可以使用Autofac进行此操作吗?

1 个答案:

答案 0 :(得分:3)

您可以创建一个工厂类,它将根据参数创建实例。

public class FooFactory : IFooFactory
{
    public delegate IFoo FooBuilder(String key);

    public FooFactory(FooBuilder fooBuilder)
    {
        this._fooBuilder = fooBuilder;
        this._foos = new ConcurrentDictionary<String, IFoo>();
    }

    private readonly FooBuilder _fooBuilder;
    private readonly ConcurrentDictionary<String, IFoo> _foos;

    public IFoo Get(String key)
    {
        IFoo foo = this._foos.GetOrAdd(key, k => this._fooBuilder(k));
        return foo;
    }
}

并将其注册为:

builder.RegisterType<Foo>()
       .As<IFoo>();
builder.RegisterType<FooFactory>()
       .As<IFooFactory>()
       .SingleInstance();
builder.Register<Func<String, IFoo>>(c => c.Resolve<IFooFactory>().Get)
       .As<Func<String, IFoo>>();

然后要解决获得IFoo,您可以依赖Func<String, IFoo>

c.Resolve<Func<String, IFoo>>()("a");