-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathDomainEventsServiceCollectionExtensions.cs
30 lines (27 loc) · 1.29 KB
/
DomainEventsServiceCollectionExtensions.cs
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
namespace ServiceControl.Infrastructure.DomainEvents
{
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
public static class DomainEventsServiceCollectionExtensions
{
/// <summary>
/// Registers provided type as event handler for all its implemented IDomainHandler interfaces as a transient component
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serviceCollection"></param>
public static void AddDomainEventHandler<T>(this IServiceCollection serviceCollection)
{
serviceCollection.Add(new ServiceDescriptor(typeof(T), typeof(T), ServiceLifetime.Transient));
var interfaces = typeof(T).GetInterfaces().Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDomainHandler<>)).ToArray();
if (!interfaces.Any())
{
throw new Exception($"{nameof(AddDomainEventHandler)} requires registered type to implement at lest one {typeof(IDomainHandler<>).Name} interface.");
}
foreach (var serviceType in interfaces)
{
serviceCollection.Add(new ServiceDescriptor(serviceType, sp => sp.GetService(typeof(T)), ServiceLifetime.Transient));
}
}
}
}