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

利用ASP.netCore自带DI(DependencyInjection)实现批量依赖注入的更多相关文章

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

    在上一章中主要和大家分享了在ASP.NET Core中如何使用Autofac替换自带DI进行构造函数的批量依赖注入,本章将和大家继续分享如何使之能够同时支持属性的批量依赖注入. 约定: 1.仓储层接口 ...

  2. ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)

    在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...

  3. ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)

    在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...

  4. [ASP.NET Core开发实战]基础篇02 依赖注入

    ASP.NET Core的底层机制之一是依赖注入(DI)设计模式,因此要好好掌握依赖注入的用法. 什么是依赖注入 我们看一下下面的例子: public class MyDependency { pub ...

  5. IOC/DI控制反转与依赖注入

    IOC/DI控制反转与依赖注入 IOC和DI表现的效果的是一样的只不过对于作用的对象不同,有了不一样的名字. 先用一个现实的例子来说明IOC/DI表现出来的效果.

  6. ASP.NETCore 3.0 Autofac替换及控制器属性注入及全局容器使用

    1.Autofac基础使用 参考: https://www.cnblogs.com/li150dan/p/10071079.html 2.ASP.NETCore 3.0 Autofac 容器替换 需要 ...

  7. ASP.NET MVC进阶之路:深入理解依赖注入(DI)和控制反转(IOC)

    0X1 什么是依赖注入 依赖注入(Dependency Injection),是这样一个过程:某客户类只依赖于服务类的一个接口,而不依赖于具体服务类,所以客户类只定义一个注入点.在程序运行过程中,客户 ...

  8. ASP.NET Core 在 JSON 文件中配置依赖注入

    前言 在上一篇文章中写了如何在MVC中配置全局路由前缀,今天给大家介绍一下如何在在 json 文件中配置依赖注入. 在以前的 ASP.NET 4+ (MVC,Web Api,Owin,SingalR等 ...

  9. Asp.Net Core 进阶(三)—— IServiceCollection依赖注入容器和使用Autofac替换它

    Asp.Net Core 提供了默认的依赖注入容器 IServiceCollection,它是一个轻量级的依赖注入容器,所以功能不多,只是提供了基础的一些功能,要实现AOP就有点麻烦,因此在实际工作当 ...

随机推荐

  1. 最新Windows下Redis集群

    实现简单的Windows下Redis集群配置,以下是配置过程中出现的几个问题: [1]逐个启动7001 7002 7003 7004 7005 7006节点时,出现createing server T ...

  2. 改变input光标颜色与输入字体颜色不同

    设置input css: color #ffd600text-shadow 0px 0px 0px #bababa -webkit-text-fill-color initial input, tex ...

  3. nginx.conf配置文件的简单说明

    #nginx 监听原理 先监听端口 --> 再配置域名 -->匹配到就访问local 否则 没有匹配到域名就默认访问第一个监听端口的local地址# vi nginx.conf user ...

  4. Ajax异步请求模板

    $.ajax({ url: '', type: 'post', data: {'id':id}, dataType: 'json', success: function(data,statusText ...

  5. 理解oracle中连接和会话

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp44 理解oracle中连接和会话 1.  概念不同:概念不同: 连接是指物 ...

  6. Spring AOP 通过order来指定顺序

    详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt398 Spring中的事务是通过aop来实现的,当我们自己写aop拦截的时候 ...

  7. 解决Android Studio中Refreshing gradle project时间过长的最简单方法

    Refreshing gradle project往往出现在Gradle出现更新,需要从墙外的网重新拖下来的前提下.具体可以查看以下文件:/path/to/project/gradle/wrapper ...

  8. 转:jquery 父、子页面之间页面元素的获取,方法的调用

    一.jQuery 父.子页面之间页面元素的获取,方法的调用: 1. 父页面获取子页面元素: 格式:$("#iframe的ID").contents().find("#if ...

  9. 201521123112《Java程序设计》第1周学习总结

    1.本周学习总结 本周通过面授课和上机课,以及在课后通过对<Java学习笔记>前一二章的阅读,初步了解了Java在计算机领域中的重要性,以及Java为什么能够这么广泛的运用在编程中.通过上 ...

  10. maven profile切换正式环境和测试环境

    有时候,我们在开发和部署的时候,有很多配置文件数据是不一样的,比如连接mysql,连接redis,一些properties文件等等 每次部署或者开发都要改配置文件太麻烦了,这个时候,就需要用到mave ...