3

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

如何将这两者结合在一起,让命名服务带有传递给构造函数的参数?

4

1 回答 1

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) { }        
}
于 2015-01-20T12:50:24.807 回答