如何将参数传递给 LightInject 中的命名服务?

How to pass a parameter to a named services in LightInject?

在 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); 

如何将这两者结合起来,将命名服务与参数传递给构造函数?

你的意思是这样?

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) { }        
}