3 changed files with 53 additions and 4 deletions
@ -0,0 +1,48 @@ |
|||||
|
using Microsoft.Extensions.DependencyInjection; |
||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Linq; |
||||
|
using System.Reflection; |
||||
|
using System.Text; |
||||
|
using System.Threading.Tasks; |
||||
|
|
||||
|
namespace Wood.Service.Controllers.RegistService |
||||
|
{ |
||||
|
public static class ServiceCollectionExtensions |
||||
|
{ |
||||
|
// 批量注册接口及其实现类(接口以I开头,实现类与接口同名去掉I)
|
||||
|
public static IServiceCollection AddServicesByConvention(this IServiceCollection services, Assembly assembly) |
||||
|
{ |
||||
|
var implementationTypes = assembly.GetTypes() |
||||
|
.Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericType); |
||||
|
|
||||
|
foreach (var implementationType in implementationTypes) |
||||
|
{ |
||||
|
var interfaces = implementationType.GetInterfaces() |
||||
|
.Where(i => i.Name == "I" + implementationType.Name); |
||||
|
|
||||
|
foreach (var @interface in interfaces) |
||||
|
{ |
||||
|
services.AddScoped(@interface, implementationType); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return services; |
||||
|
} |
||||
|
|
||||
|
// 批量注册特定接口的所有实现类
|
||||
|
public static IServiceCollection AddImplementationsOf<TInterface>(this IServiceCollection services, Assembly assembly, ServiceLifetime lifetime = ServiceLifetime.Scoped) |
||||
|
{ |
||||
|
var interfaceType = typeof(TInterface); |
||||
|
var implementationTypes = assembly.GetTypes() |
||||
|
.Where(t => !t.IsInterface && !t.IsAbstract && interfaceType.IsAssignableFrom(t)); |
||||
|
|
||||
|
foreach (var implementationType in implementationTypes) |
||||
|
{ |
||||
|
services.Add(new ServiceDescriptor(interfaceType, implementationType, lifetime)); |
||||
|
} |
||||
|
|
||||
|
return services; |
||||
|
} |
||||
|
} |
||||
|
} |
Loading…
Reference in new issue