需求背景:自定义类库程序中的类文件引用IService接口对象并实现依赖注入。
1.修改应用程序Program.cs文件
1 var builder = WebApplication.CreateBuilder(args); 2 builder.Services.AddProgramService(); 3 4 5 var app = builder.Build(); 6 InternalApp.ServiceProvider = app.Services;
2.服务注册
1 public static class DIServiceExtensions 2 { 3 public static void AddProgramService(this IServiceCollection services) 4 { 5 string[] clas = new string[] { "XX.Repository", "XX.Service" }; 6 foreach (string c in clas) 7 { 8 Register(services, c); 9 } 10 } 11 12 private static void Register(IServiceCollection services,string item) 13 { 14 Assembly assembly = Assembly.Load(item); 15 foreach(var type in assembly.GetTypes()) 16 { 17 var serviceAttribute = type.GetCustomAttribute<AppServiceAttribute>(); 18 19 if(serviceAttribute != null) 20 { 21 var serviceType = serviceAttribute.ServiceType; 22 if(serviceType == null && serviceAttribute.InterfaceServiceType) 23 { 24 serviceType = type.GetInterfaces().FirstOrDefault(); 25 } 26 if(serviceType == null) 27 { 28 serviceType = type; 29 } 30 31 switch(serviceAttribute.ServiceLifetime) 32 { 33 case LifeTime.Singleton: 34 services.AddSingleton(serviceType,type); 35 break; 36 case LifeTime.Scoped: 37 services.AddScoped(serviceType, type); 38 break; 39 case LifeTime.Transient: 40 services.AddTransient(serviceType, type); 41 break; 42 default: 43 services.AddTransient(serviceType, type); 44 break; 45 } 46 47 System.Console.WriteLine($"注册:{serviceType}"); 48 } 49 } 50 } 51 }
3. 新建InternalApp类文件
1 public static class InternalApp 2 { 3 /// <summary> 4 /// 应用服务 5 /// </summary> 6 public static IServiceProvider ServiceProvider; 7 }
4. 新建GlobalContext.cs文件
1 public static class GlobalContext 2 { 3 /// <summary> 4 /// 服务提供器 5 /// </summary> 6 public static IServiceProvider ServiceProvider => InternalApp.ServiceProvider; 7 8 /// <summary> 9 /// 获取请求生命周期的服务 10 /// </summary> 11 /// <param name="type"></param> 12 /// <returns></returns> 13 public static object GetService(Type type) 14 { 15 return ServiceProvider.GetService(type); 16 } 17 18 public static TService GetService<TService>() where TService : class 19 { 20 return GetService(typeof(TService)) as TService; 21 } 22 }
5. 类文件调用服务对象
1 public class A 2 { 3 private readonly IAService _AService = GlobalContext.GetService<IAService>(); 4 }
标签:serviceType,ServiceProvider,static,Net6,services,IServiceProvider,全局,type,public From: https://www.cnblogs.com/mingcore/p/18140092