根据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并根据“值”获得正确的实现。
var typedFooFactory = container.GetInstance<IFooFactory>();
var foo = typedFooFactory.GetFoo(3);
Assert.AreEqual(foo.GetType(),typeof(AnotherFooThatImplementsIFoo));
答案 0 :(得分:1)
关键是要记住在我们工厂的GetFoo方法中,我们不是调用委托,而只是传递对它的引用。调用是在我们注册工厂时(通过实例化Foo对象)。 所以我做的是创建一个静态的Factory类,它基于&#34; value&#34;生成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对象属于Type AnotherFooThatImplementsIFoo
Assert.AreEqual(foo.GetType(),typeof(AnotherFooThatImplementsIFoo));