在LightInject中,注册一个命名服务如下:
container.Register<IFoo, Foo>();
container.Register<IFoo, AnotherFoo>("AnotherFoo");
var instance = container.GetInstance<IFoo>("AnotherFoo");
带参数的服务:
container.Register<int, IFoo>((factory, value) => new Foo(value));
var fooFactory = container.GetInstance<Func<int, IFoo>>();
var foo = (Foo)fooFactory(42);
如何将这两者结合起来,使命名服务的参数传递给构造函数?
答案 0 :(得分:4)
你的意思是这样吗?
class Program
{
static void Main(string[] args)
{
var container = new ServiceContainer();
container.Register<string,IFoo>((factory, s) => new Foo(s), "Foo");
container.Register<string, IFoo>((factory, s) => new AnotherFoo(s), "AnotherFoo");
var foo = container.GetInstance<string, IFoo>("SomeValue", "Foo");
Debug.Assert(foo.GetType().IsAssignableFrom(typeof(Foo)));
var anotherFoo = container.GetInstance<string, IFoo>("SomeValue", "AnotherFoo");
Debug.Assert(anotherFoo.GetType().IsAssignableFrom(typeof(AnotherFoo)));
}
}
public interface IFoo { }
public class Foo : IFoo
{
public Foo(string value){}
}
public class AnotherFoo : IFoo
{
public AnotherFoo(string value) { }
}