实现类:
public interface IPerson { string Get(); } public class PersonA:IPerson { public string Get() { return "PersonA"; } } public class PersonB : IPerson { public string Get() { return "PersonB"; } }
ConfigureService:
services.AddSingleton<PersonA>(); services.AddSingleton<PersonB>(); services.AddSingleton(provider => { Func<string, IPerson> accesor = (key) => { if (key == "a") { return provider.GetService<PersonA>(); } else if (key == "b") { return provider.GetService<PersonB>(); } else { throw new ArgumentException("key error"); } }; return accesor; });
控制器:
public HomeController(Func<string,IPerson> func) { var personA = func("a"); var personB = func("b"); Console.WriteLine(personA.Get()); Console.WriteLine(personB.Get()); string a = ""; }
...