首页 > 其他 > 详细

Startup 批量注入

时间:2021-09-11 21:15:11      阅读:21      评论:0      收藏:0      [点我收藏+]

1、创建三个标签接口 IScoped、ISingleton、ITransient

2、创建要开发的业务接口根据业务需求并继承上面三个标签的一个 public interface IUserService: IScoped

3、创建注入方法

public static class DataServiceExtension
{
/// <summary>
/// 注入数据
/// </summary>
/// <param name="services"></param>
public static IServiceCollection AddDataService(this IServiceCollection services)
{
#region 依赖注入
//services.AddScoped<IUserService, UserService>();
var baseType = typeof(IScoped);//IScoped、ISingleton、ITransient
var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
var referencedAssemblies = System.IO.Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFrom).ToArray();
var types = referencedAssemblies
.SelectMany(a => a.DefinedTypes)
.Select(type => type.AsType())
.Where(x => x != baseType && baseType.IsAssignableFrom(x)).ToArray();
var implementTypes = types.Where(x => x.IsClass).ToArray();
var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
foreach (var implementType in implementTypes)
{
var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
if (interfaceType != null)
services.AddScoped(interfaceType, implementType);
// services.AddSingleton(interfaceType, implementType);
// services.AddTransient(interfaceType, implementType);
}

#endregion

return services;
}
}

4、在startup里添加方法就完成了

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDataService();
}

5、在控制器中使用就行了

技术分享图片

 

Startup 批量注入

原文:https://www.cnblogs.com/DailyRecord/p/15251376.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!