gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:19:28 25 4
gpt4 key购买 nike

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

关于light-inject - 如何将参数传递给 LightInject 中的命名服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28021095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com