-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServiceRegistrationSetup.cs
More file actions
47 lines (41 loc) · 1.89 KB
/
ServiceRegistrationSetup.cs
File metadata and controls
47 lines (41 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using Microsoft.Extensions.DependencyInjection;
namespace AutoServiceRegistration.AspNetCore;
public static class ServiceRegistrationSetup
{
public static IServiceCollection AddRegisterServices(this IServiceCollection services) =>
services
.AddServices(typeof(ISingletonService), ServiceLifetime.Singleton)
.AddServices(typeof(IScopedService), ServiceLifetime.Scoped)
.AddServices(typeof(ITransientService), ServiceLifetime.Transient);
private static IServiceCollection AddServices(this IServiceCollection services, Type interfaceType,
ServiceLifetime lifetime)
{
var interfaceTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(type => interfaceType.IsAssignableFrom(type)
&& type.IsClass
&& !type.IsAbstract)
.SelectMany(type => type.GetInterfaces()
.Where(interfaceType.IsAssignableFrom)
.Select(service => new
{
Service = service,
Implementation = type
})
);
foreach (var type in interfaceTypes)
{
services.AddService(type.Service!, type.Implementation, lifetime);
}
return services;
}
private static IServiceCollection AddService(this IServiceCollection services, Type serviceType,
Type implementationType, ServiceLifetime lifetime) =>
lifetime switch
{
ServiceLifetime.Singleton => services.AddSingleton(serviceType, implementationType),
ServiceLifetime.Scoped => services.AddScoped(serviceType, implementationType),
ServiceLifetime.Transient => services.AddTransient(serviceType, implementationType),
_ => throw new ArgumentException("Invalid lifeTime", nameof(lifetime))
};
}