LightInject使用参数类型化工厂



根据LightInject的文档,我们可以创建一个类型化的工厂,并向其传递一个值,如下所示:

public class Foo : IFoo
{
   public Foo(int value)
   {
       Value = value;
   }
   public int Value { get; private set; }
}
public interface IFooFactory
{
    IFoo GetFoo(int value);
}
public class FooFactory : IFooFactory
{
    private Func<int, IFoo> createFoo;
    public FooFactory(Func<int, IFoo> createFoo)
    {
        this.createFoo = createFoo;
    }
    public IFoo GetFoo(int value)
    {
        return createFoo(value);
    }
}

我们这样注册:

container.Register<int, IFoo>((factory, value) => new Foo(value));
container.Register<IFooFactory, FooFactory>(new PerContainerLifetime());

我们可以这样称呼GetFoo:

var typedFooFactory = container.GetInstance<IFooFactory>();
var foo = typedFooFactory.GetFoo(42);

所以现在我的问题是:当我们注册工厂新的foo(值)时,我们显式地实例化foo。但是,如果我们想在基于值的GetFoo方法中执行该操作,该怎么办?

public IFoo GetFoo(int value)
{
    switch (value)
    {
         case 1: return new Foo(1);
         case 2: return new FooThatImplementsIFoo(2);
         case 3: return new AnotherFooThatImplementsIFoo(3);
         default: return null;
    }
}

我希望能够调用GetFoo并获得基于"value"的正确实现。

var typedFooFactory = container.GetInstance<IFooFactory>();
var foo = typedFooFactory.GetFoo(3); 
Assert.AreEqual(foo.GetType(),typeof(AnotherFooThatImplementsIFoo));

关键是要记住,在我们工厂的GetFoo方法中,我们不是在调用委托,而是只传递对它的引用。调用是在我们注册工厂时(通过实例化Foo对象)。因此,我所做的是创建一个静态Factory类,该类基于"值"生成IFoo的实现:

container.Register<int, IFoo>((factory, value) => FooFactory.GetInstance);

我的FooFactory是这样的:

public static class FooFactory
{
    public static IFoo GetInstance(IServiceFactory serviceFactory, int value)
    {
        switch (value)
        {
            case 1:
            {
                return serviceFactory.GetInstance<Foo>();
            }
            case 2:
            {
                return serviceFactory.GetInstance<FooThatImplementsIFoo>();
            }
            case 3:
            {
                return serviceFactory.GetInstance<AnotherFooThatImplementsIFoo>();
            }
            default:
            {
                return null;
            }
        }
    }
}

因此,我通过以下操作调用代理:

var typedFooFactory = container.GetInstance<IFooFactory>();
var foo = typedFooFactory.GetFoo(3); 

现在我的foo对象的类型是AnotherFooThatImplementsIFoo

Assert.AreEqual(foo.GetType(),typeof(AnotherFooThatImplementsIFoo));

相关内容

  • 没有找到相关文章

最新更新