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、在控制器中使用就行了
原文:https://www.cnblogs.com/DailyRecord/p/15251376.html