zoukankan      html  css  js  c++  java
  • ASP.NET Core-一个服务多个不同实现依赖注入

    实现类:

        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 = "";
            }

    ...

  • 相关阅读:
    doc
    doc
    doc
    doc
    doc
    doc
    doc
    doc
    java基础知识系列--- 反射,注解,泛型,内省
    CCProcxy代理服务器的配置使用
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/12402755.html
Copyright © 2011-2022 走看看