文档地址
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0
添加类:
添加服务
Controller中使用
视图中使用
程序集依赖注入
把所有的类型和接口放进类库中:
核心代码:
/// <summary> /// 程序集依赖注入 /// </summary> /// <param name="services"></param> /// <param name="assemblyName"></param> /// <param name="serviceLifetime"></param> public static void AddAssembly(this IServiceCollection services, string assemblyName, ServiceLifetime serviceLifetime) { if (services == null) { throw new ArgumentNullException((nameof(services) + "为空")); } if (string.IsNullOrEmpty(assemblyName)) { throw new ArgumentNullException((nameof(assemblyName) + "为空")); } //根据 AssemblyName 解析并加载程序集。 var assemblyByName = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName)); if (assemblyByName == null) { throw new DllNotFoundException(nameof(assemblyByName) + ".dll不存在"); } //获取当前实例的 Type var types = assemblyByName.GetTypes(); //获取不是值类型或接口类型、不为抽象类、泛型类型的程序集 var list = types.Where(x => x.IsClass && !x.IsAbstract && !x.IsGenericType).ToList(); foreach (var type in list) { //获取由当前 Type 实现或继承的所有接口。 var iList = type.GetInterfaces(); //确定序列中是否存在任意一个元素满足条件。 if (iList.Any()) { var i = iList.First(); //选择依赖注入类型 switch (serviceLifetime) { case ServiceLifetime.Singleton: services.AddSingleton(i, type); break; case ServiceLifetime.Scoped: services.AddScoped(i, type); break; case ServiceLifetime.Transient: services.AddTransient(i, type); break; } } } }
注入服务:
调用: