zoukankan      html  css  js  c++  java
  • 利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入

    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[]>();
            }

    注册:

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

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

    改为:

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

     完整代码:

    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[]>();
            }
        }
    }
  • 相关阅读:
    字串变换
    重建道路
    poj3278 Catch That Cow
    机器人搬重物
    [HNOI2004]打鼹鼠
    曼哈顿距离
    邮票面值设计
    poj1101 The Game
    解决了一个堆破坏问题
    模型资源从无到有一条龙式体验
  • 原文地址:https://www.cnblogs.com/xiaoliangge/p/7642372.html
Copyright © 2011-2022 走看看