在存储库中,我保留了一些在应用程序的整个生命周期中都存在的实例,但有时我需要立即用另一个实例和LightInject替换这些实例,即使将新实例传递到容器中也是如此。GetInstance构造函数重写。
以下是显示问题的片段:
internal class ClassA
{
public string Name { get; private set; }
public ClassA(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
internal class ClassB
{
public ClassA A { get; private set; }
public ClassB(ClassA a)
{
A = a;
}
public override string ToString()
{
return string.Format("I contain {0}", A);
}
}
private void TestContainer()
{
var container = new LightInject.ServiceContainer();
var a1 = new ClassA("A instance 1");
container.Register(x => a1);
container.Register<ClassB>();
var a2 = new ClassA("A instance 2");
var bwitha1 = container.GetInstance<ClassB>();
if(bwitha1.A != a1)
{
throw new InvalidOperationException("This will not happen");
}
var bwitha2 = container.GetInstance<ClassA, ClassB>(a2);
if(bwitha2.A != a2)
{
throw new InvalidOperationException("Something went wrong here");
}
}
如果我在GetInstance调用中给出显式实例,为什么LightInject以前注册的实例优先?如何绕过这个问题,并使用其中一个参数的替代实例来构造对象?
在当前版本的LightInject中,如果要使用运行时参数,则需要提供一个工厂。
以下解决方法可能适用于您。
using LightInject;
class Program
{
static void Main(string[] args)
{
var container = new ServiceContainer();
container.Register<Bar>();
container.Register<Foo>();
container.Register<Bar, Foo>((factory, bar) => new Foo(bar), "FooWithRuntimeArgument");
var instance = container.GetInstance<Foo>();
var instanceWithRuntimeArgument = container.GetInstance<Bar, Foo>(new Bar(), "FooWithRuntimeArgument");
}
}
public class Foo
{
public Foo(Bar bar) {}
}
public class Bar {}