当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

2019年01月08日  | 移动技术网IT编程  | 我要评论

第十一届全国美展,霍州租房信息,岗位大练兵总结

最近有个需求就是一个抽象仓储层接口方法需要sqlserver以及oracle两种实现方式,为了灵活我在依赖注入的时候把这两种实现都给注入进了依赖注入容器中,但是在服务调用的时候总是获取到最后注入的那个方法的实现,这时候就在想能不能实现动态的选择使用哪种实现呢?如果可以的话那么我只需要在配置文件中进行相应的配置即可获取到正确的实现方法的调用,这样的话岂不快哉!今天我们就来一起探讨下实现这种需求的几种实现方式吧。

作者:依乐祝
原文地址:

代码演示

在开始实现的方式之前,我们先模拟下代码。由于真实系统的结构比较复杂,所以这里我就单独建一个类似的项目结构代码。项目如下图所示:

1546866490439

接下来我来详细说下上面的结果作用及代码。

  1. multiimpdemo.i 这个项目是接口项目,里面有一个简单的接口定义isayhello,代码如下:

        public interface isayhello
        {
            string talk();
        }

    很简单,就一个模拟讲话的方法。

  2. multiimpdemo.a 这个类库项目是接口的一种实现方式,里面有一个sayhello类用来实现isayhello接口,代码如下:

    /**
    *┌──────────────────────────────────────────────────────────────┐
    *│ 描    述:                                                    
    *│ 作    者:yilezhu                                             
    *│ 版    本:1.0                                                 
    *│ 创建时间:2019/1/7 17:41:33                             
    *└──────────────────────────────────────────────────────────────┘
    *┌──────────────────────────────────────────────────────────────┐
    *│ 命名空间: multiimpdemo.a                                   
    *│ 类    名: sayhello                                      
    *└──────────────────────────────────────────────────────────────┘
    */
    using multiimpdemo.i;
    using system;
    using system.collections.generic;
    using system.text;
    
    namespace multiimpdemo.a
    {
        public class sayhello : isayhello
        {
            public string talk()
            {
                return "talk from a.sayhello";
            }
        }
    }
  3. multiimpdemo.b 这个类库项目是接口的另一种实现方式,里面也有一个sayhello类用来实现isayhello接口,代码如下:

    /**
    *┌──────────────────────────────────────────────────────────────┐
    *│ 描    述:                                                    
    *│ 作    者:yilezhu                                             
    *│ 版    本:1.0                                                 
    *│ 创建时间:2019/1/7 17:41:45                             
    *└──────────────────────────────────────────────────────────────┘
    *┌──────────────────────────────────────────────────────────────┐
    *│ 命名空间: multiimpdemo.b                                   
    *│ 类    名: sayhello                                      
    *└──────────────────────────────────────────────────────────────┘
    */
    using multiimpdemo.i;
    using system;
    using system.collections.generic;
    using system.text;
    
    namespace multiimpdemo.b
    {
        public class sayhello:isayhello
        {
            public string talk()
            {
                return "talk from b.sayhello";
            }
        }
    }
    
  4. multiimpdemo.show 这个就是用来显示我们模拟效果的api项目,首选我们在configureservices中加入如下的代码来进行上述两种实现方式的注入:

     services.addtransient<isayhello, multiimpdemo.a.sayhello>();
     services.addtransient<isayhello, multiimpdemo.b.sayhello>();
  5. 在api实现里面获取服务并进行模拟调用:

      private readonly isayhello sayhello;
    
            public valuescontroller(isayhello sayhello)
            {
                this.sayhello = sayhello;
            }
    
            // get api/values
            [httpget]
            public actionresult<ienumerable<string>> get()
            {
                return new string[] { sayhello.talk() };
            }
    

    代码很简单对不对?你应该看的懂吧,这时候我们运行起来项目,然后访问api'api/values'这个接口,结果总是显示如下的结果:

    1546867091226

两种需求对应两种实现

这里有两种业务需求!第一种业务中只需要对其中一种实现方式进行调用,如:业务需要sqlserver数据库的实现就行了。第二种是业务中对这两种实现方式都有用到,如:业务急需要用到oracle的数据库实现同时也有用到sqlserver的数据库实现,需要同时往这两个数据库中插入相同的数据。下面分别对这两种需求进行解决。

业务中对这两种实现方式都有用到

针对这种情况有如下两种实现方式:

  1. 第二种实现方式

    其实,在asp.net core中,当你对一个接口注册了多个实现的时候,构造函数是可以注入一个该接口集合的,这个集合里是所有注册过的实现。

    下面我们先改造下configureservices,分别注入下这两种实现

    services.addtransient<isayhello, a.sayhello>();
    services.addtransient<isayhello,b.sayhello>();

    接着继续改造下注入的方式,这里我们直接注入ienumerable<isayhello>如下代码所示:

    private readonly isayhello sayhelloa;
            private readonly isayhello sayhellob;
            public valuescontroller(ienumerable<isayhello> sayhellos)
            {
                sayhelloa = sayhellos.firstordefault(h => h.gettype().namespace == "multiimpdemo.a");
                sayhellob = sayhellos.firstordefault(h => h.gettype().namespace == "multiimpdemo.b");
            }
    
    
            // get api/values
            [httpget]
            public actionresult<ienumerable<string>> get()
            {
                return new string[] { sayhelloa.talk() , sayhellob.talk()};
            } 
    

    然后运行起来看下效果吧

    1546870734607

  2. 利用addtransient的扩展方法public static iservicecollection addtransient<tservice>(this iservicecollection services, func<iserviceprovider, tservice> implementationfactory) where tservice : class; 然后根据我们的配置的实现来进行服务实现的获取。下面就让我们利用代码来实现一番吧:

      services.addtransient<a.sayhello>();
                services.addtransient<b.sayhello>();
    
                services.addtransient(implementationfactory =>
                {
                    func<string, isayhello> accesor = key =>
                    {
                        if (key.equals("multiimpdemo.a"))
                        {
                            return implementationfactory.getservice<a.sayhello>();
                        }
                        else if (key.equals("multiimpdemo.b"))
                        {
                            return implementationfactory.getservice<b.sayhello>();
                        }
                        else
                        {
                            throw new argumentexception($"not support key : {key}");
                        }
                    };
                    return accesor;
                });
    

    当然了,既然用到了我们配置文件中的代码,因此我们需要设置下这个配置:

    然后我们具体调用的依赖注入的方式需要变化一下:

    private readonly isayhello sayhelloa;
            private readonly isayhello sayhellob;
    
            private readonly func<string, isayhello> _serviceaccessor;
    
            public valuescontroller(func<string, isayhello> serviceaccessor)
            {
                this._serviceaccessor = serviceaccessor;
    
                sayhelloa = _serviceaccessor("multiimpdemoa");
                sayhellob = _serviceaccessor("multiimpdemob");
            }
    
    
            // get api/values
            [httpget]
            public actionresult<ienumerable<string>> get()
            {
                return new string[] { sayhelloa.talk() , sayhellob.talk()};
            }

    然后运行看下效果吧:

    1546869793187

    可以看到a跟b的实现都获取到了!效果实现!

业务只需要对其中一种实现方式的调用

这时候我们可以根据我们预设的配置来动态获取我们所需要的实现。这段话说的我自己都感觉拗口。话不多少,开鲁吧!这里我将介绍三种实现方式。

  1. 根据我们的配置文件中设置的key来进行动态的注入。

    这种方式实现之前首先得进行相应的配置,如下所示:

      "commonsettings": {
        "implementassembly": "multiimpdemo.a"
      }

    然后在注入的时候根据配置进行动态的进行注入:

     services.addtransient<isayhello, a.sayhello>();
                services.addtransient<isayhello, b.sayhello>();

    然后在服务调用的时候稍作修改:

      private readonly isayhello sayhello;
            public valuescontroller(ienumerable<isayhello> sayhellos,iconfiguration configuration)
            {
                sayhello = sayhellos.firstordefault(h => h.gettype().namespace == configuration.getsection("commonsettings:implementassembly").value);
            }
    
    
            // get api/values
            [httpget]
            public actionresult<ienumerable<string>> get()
            {
                return new string[] { sayhello.talk() };
            }

    ok,到这里运行一下看下效果吧!然后改下配置文件再看下效果!

    1546871452531

  2. 第二种实现方式,即接口参数的方式这样可以避免上个方法中反射所带来的性能损耗。

    这里我们改造下接口,接口中加入一个程序集的属性,如下所示:

    public interface isayhello
        {
            string implementassemblyname { get; }
            string talk();
        }

    对应的a跟b中的实现代码也要少做调整:

    a:

     public string implementassemblyname => "multiimpdemo.a";
    
            public string talk()
            {
                return "talk from a.sayhello";
            }

    b:

     public string implementassemblyname => "multiimpdemo.b";
    
            public string talk()
            {
                return "talk from b.sayhello";
            }

    然后,在实现方法调用的时候稍微修改下:

     private readonly isayhello sayhello;
            public valuescontroller(ienumerable<isayhello> sayhellos,iconfiguration configuration)
            {
                sayhello = sayhellos.firstordefault(h => h.implementassemblyname == configuration.getsection("commonsettings:implementassembly").value);
            }
    
    
            // get api/values
            [httpget]
            public actionresult<ienumerable<string>> get()
            {
                return new string[] { sayhello.talk() };
            }
    

    效果自己运行下看下吧!

  3. 第三种实现是根据配置进行动态的注册

    首先修改下configureservices方法:

     var implementassembly = configuration.getsection("commonsettings:implementassembly").value;
                if (string.isnullorwhitespace(implementassembly)) throw new argumentnullexception("commonsettings:implementassembly未配置");
                if (implementassembly.equals("multiimpdemo.a"))
                {
                    services.addtransient<isayhello, a.sayhello>();
    
                }
                else
                {
                    services.addtransient<isayhello, b.sayhello>();
    
                }

    这样的话就会根据我们的配置文件来进行动态的注册,然后我们像往常一样进行服务的调取即可:

      private readonly isayhello _sayhello;
            public valuescontroller(isayhello sayhello)
            {
                _sayhello = sayhello;
            }
    
    
            // get api/values
            [httpget]
            public actionresult<ienumerable<string>> get()
            {
                return new string[] { _sayhello.talk() };
            }

    运行即可得到我们想要的效果!

总结

本文从具体的业务需求入手,根据需求来或动态的进行对应服务的获取,或同时使用两个不同的实现!希望对您有所帮助!如果您有更多的实现方法可以在下方留言,或者加入.net core实战千人群跟637326624大伙进行交流,最后感谢您的阅读!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网