利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入

Posted DotNet开发跳槽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入相关的知识,希望对你有一定的参考价值。

来源 http://www.cnblogs.com/xiaoliangge/p/7642372.html

ASP.net Core自带DI(依赖注入),用法如下:

services.AddScoped(typeof(IProductService), typeof(ProductService));

如果服务较多,必定造成文件难以维护

所以需要利用反射批量实现注册

核心代码如下:

一个类可能间接继承了多个接口(例如:public 和internal的接口),这里我们就以实现类为Key,所继承的接口为value构造一个集合

     /// <summary>  
        /// 获取程序集中的实现类对应的多个接口
        /// </summary>  
        /// <param name="assemblyName">程序集</param>
        public Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!String.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.Load(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces();
                    result.Add(item, interfaceType);
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }

利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入

注册:

我们现在可以把具体的注册例如

services.AddScoped(typeof(IProductService), typeof(ProductService));

改为:

利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入

        //集中注册服务
            foreach (var item in GetClassName("Service"))
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }

利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入

 完整代码:

利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Entity.Table;
using DAL;
using System.Reflection;
using Service;

namespace ASP.NetCoreAPI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ProductContext>(options =>
                options.Usemysql(Configuration.GetConnectionString("MySqlConnection")));//添加Mysql支持

            //集中注册服务
            foreach (var item in GetClassName("Service"))
            {
                foreach (var typeArray in item.Value)
                {
                    services.AddScoped(typeArray, item.Key);
                }
            }
            services.AddUnitOfWork<ProductContext>();//添加UnitOfWork支持
                                                     //services.AddScoped(typeof(IProductService), typeof(ProductService));//用ASP.NET Core自带依赖注入(DI)注入使用的类
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }

        /// <summary>  
        /// 获取程序集中的实现类对应的多个接口
        /// </summary>  
        /// <param name="assemblyName">程序集</param>
        public Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!String.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.Load(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces();
                    result.Add(item, interfaceType);
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }
    }
}


以上是关于利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core 依赖注入(DI)

ASP.NET Core Web 应用程序系列- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)

依赖注入[6]: .NET Core DI编程体验

ASP.NET Core Web 应用程序系列- 在ASP.NET Core中使用Autofac替换自带DI进行构造函数和属性的批量依赖注入(MVC当中应用)

asp.netcore di 实现批量接口注入

ASP.NET Core 2 - 多个 Azure Redis 缓存服务 DI