.net Core 批量依赖注入

这篇博客介绍了如何在ASP.NET Core应用中通过自定义的IServiceCollection扩展方法批量注入接口及其实现类。在`Startup`类的`ConfigureServices`方法中调用此扩展方法,可以简化服务注册过程,提高代码的可读性和效率。
摘要由CSDN通过智能技术生成

1.添加IServiceCollection的扩展方法

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Demo.Web.Extension
{
    public static class ServicesExtension
    {

        /// <summary>
        /// 批量注入
        /// </summary>
        /// <param name="services">扩张对象</param>
        /// <param name="interfaceAssembly">接口</param>
        /// <param name="implementAssembly">实现类</param>
        public static void AddTransientExtension(this IServiceCollection services, Assembly interfaceAssembly, Assembly implementAssembly)
        {
            var interfaces = interfaceAssembly.GetTypes().Where(t => t.IsInterface);//拿到项目中所有接口
            var implements = implementAssembly.GetTypes();//拿到项目中所有类和接口
            foreach (var item in interfaces)
            {
                //判断是否实现了该接口,实现了就直接注入
                var type = implements.FirstOrDefault(x => item.IsAssignableFrom(x));
                if (type != null)
                {
                    services.AddTransient(item, type);
                }
            }
        }
    }
}

2.然后直接在startup中的ConfigureServices方法中调用该扩展方法就ok了

        services.AddTransientExtension(Assembly.Load("Demo.BLL.Interface"),Assembly.Load("Demo.BLL"));//批量注入

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值