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"));//批量注入