-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDependencyInjectionEventBusBuilder.cs
More file actions
73 lines (62 loc) · 2.73 KB
/
DependencyInjectionEventBusBuilder.cs
File metadata and controls
73 lines (62 loc) · 2.73 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and ReflectionEventing Contributors.
// All Rights Reserved.
using ReflectionEventing.DependencyInjection.Services;
namespace ReflectionEventing.DependencyInjection;
/// <summary>
/// Represents a builder for configuring the event bus with .NET Core's built-in dependency injection.
/// </summary>
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class DependencyInjectionEventBusBuilder(IServiceCollection services) : EventBusBuilder
{
internal Type QueueBackgroundService { get; set; } = typeof(DependencyInjectionQueueProcessor);
/// <summary>
/// Adds a consumer to the event bus and <see cref="IServiceCollection"/> with a specified service lifetime.
/// </summary>
/// <param name="consumerType">The type of the consumer to add.</param>
/// <param name="lifetime">The service lifetime of the consumer.</param>
/// <returns>The current instance of <see cref="EventBusBuilder"/>.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the consumer is already registered with a different lifetime or if the consumer is not registered in the service collection.
/// </exception>
public virtual EventBusBuilder AddConsumer(
#if NET5_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
#endif
Type consumerType,
ServiceLifetime lifetime
)
{
ServiceDescriptor? descriptor = services.FirstOrDefault(d => d.ServiceType == consumerType);
if (descriptor is not null)
{
if (descriptor.Lifetime != lifetime)
{
throw new InvalidOperationException(
"Event consumer must be registered with the same lifetime as the one provided."
);
}
return base.AddConsumer(consumerType);
}
services.Add(new ServiceDescriptor(consumerType, consumerType, lifetime));
return base.AddConsumer(consumerType);
}
/// <inheritdoc />
public override EventBusBuilder AddConsumer(
#if NET5_0_OR_GREATER
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
#endif
Type consumerType
)
{
ServiceDescriptor? descriptor = services.FirstOrDefault(d => d.ServiceType == consumerType);
if (descriptor is null)
{
throw new InvalidOperationException(
"Event consumer must be registered in the service collection."
);
}
return base.AddConsumer(consumerType);
}
}