当前位置:首页 > Web开发 > 正文

/// summary /// IServiceCollection扩展 /// /summary public st

2024-03-31 Web开发

/// <summary> /// IServiceCollection扩展 /// </summary> public static class ServiceExtension { /// <summary> /// 用DI批量注入接口措施集中对应的实现类。 /// <para> /// 需要注意的是,这里有如下约定: /// IUserService --> UserService, IUserRepository --> UserRepository. /// </para> /// </summary> /// <param></param> /// <param>接口措施集的名称(不包罗文件扩展名)</param> /// <returns></returns> public static IServiceCollection RegisterAssembly(this IServiceCollection service, string interfaceAssemblyName) { if (service == null) throw new ArgumentNullException(nameof(service)); if (string.IsNullOrEmpty(interfaceAssemblyName)) throw new ArgumentNullException(nameof(interfaceAssemblyName)); var assembly = RuntimeService.GetAssembly(interfaceAssemblyName); if (assembly == null) { throw new DllNotFoundException($"the dll \"{interfaceAssemblyName}\" not be found"); } //过滤失非接口及泛型接口 var types = assembly.GetTypes().Where(t => t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsGenericType); foreach (var type in types) { var implementTypeName = type.Name.Substring(1); var implementType = RuntimeService.GetImplementType(implementTypeName, type); if (implementType != null) service.AddSingleton(type, implementType); } return service; } /// <summary> /// 用DI批量注入接口措施集中对应的实现类。 /// </summary> /// <param></param> /// <param>接口措施集的名称(不包罗文件扩展名)</param> /// <param>实现措施集的名称(不包罗文件扩展名)</param> /// <returns></returns> public static IServiceCollection RegisterAssembly(this IServiceCollection service, string interfaceAssemblyName, string implementAssemblyName) { if (service == null) throw new ArgumentNullException(nameof(service)); if (string.IsNullOrEmpty(interfaceAssemblyName)) throw new ArgumentNullException(nameof(interfaceAssemblyName)); if (string.IsNullOrEmpty(implementAssemblyName)) throw new ArgumentNullException(nameof(implementAssemblyName)); var interfaceAssembly = RuntimeService.GetAssembly(interfaceAssemblyName); if (interfaceAssembly == null) { throw new DllNotFoundException($"the dll \"{interfaceAssemblyName}\" not be found"); } var implementAssembly = RuntimeService.GetAssembly(implementAssemblyName); if (implementAssembly == null) { throw new DllNotFoundException($"the dll \"{implementAssemblyName}\" not be found"); } //过滤失非接口及泛型接口 var types = interfaceAssembly.GetTypes().Where(t => t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsGenericType); foreach (var type in types) { //过滤失抽象类、泛型类以及非class var implementType = implementAssembly.DefinedTypes .FirstOrDefault(t => t.IsClass && !t.IsAbstract && !t.IsGenericType && t.GetInterfaces().Any(b => b.Name == type.Name)); if (implementType != null) { service.AddSingleton(type, implementType.AsType()); } } return service; } }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32771.html