Skip to content

Commit e839444

Browse files
authored
Merge pull request #1078 from Emopusta/refactor-open-behavior-entity
Add validation and comments to OpenBehavior entity.
2 parents 2841be9 + baa26be commit e839444

File tree

1 file changed

+37
-4
lines changed

1 file changed

+37
-4
lines changed
Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,53 @@
1-
using System;
21
using Microsoft.Extensions.DependencyInjection;
2+
using System;
3+
using System.Linq;
34

45
namespace MediatR.Entities;
56
/// <summary>
6-
/// Creates open behavior entity.
7+
/// Represents a registration entity for pipeline behaviors with a specified service lifetime.
78
/// </summary>
89
public class OpenBehavior
910
{
11+
/// <summary>
12+
/// Initializes a new instance of the <see cref="OpenBehavior"/> class.
13+
/// </summary>
14+
/// <param name="openBehaviorType">The type of the pipeline behavior to register.</param>
15+
/// <param name="serviceLifetime">The lifetime of the registered service. Defaults to Transient.</param>
16+
/// <exception cref="InvalidOperationException">Thrown if the specified type does not implement IPipelineBehavior.</exception>
17+
/// <exception cref="ArgumentNullException">Thrown if <paramref name="openBehaviorType"/> is null.</exception>
1018
public OpenBehavior(Type openBehaviorType, ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
1119
{
20+
ValidatePipelineBehaviorType(openBehaviorType);
1221
OpenBehaviorType = openBehaviorType;
1322
ServiceLifetime = serviceLifetime;
1423
}
1524

16-
public Type? OpenBehaviorType { get; }
25+
/// <summary>
26+
/// The type of the open behavior.
27+
/// </summary>
28+
public Type OpenBehaviorType { get; }
29+
30+
/// <summary>
31+
/// The service lifetime of the open behavior.
32+
/// </summary>
1733
public ServiceLifetime ServiceLifetime { get; }
1834

19-
35+
/// <summary>
36+
/// Validates whether the specified type implements the <see cref="IPipelineBehavior{TRequest, TResponse}"/> interface.
37+
/// </summary>
38+
/// <param name="openBehaviorType">The type to validate.</param>
39+
/// <exception cref="InvalidOperationException">Thrown if the type does not implement <see cref="IPipelineBehavior{TRequest, TResponse}"/>.</exception>
40+
/// <exception cref="ArgumentNullException">Thrown if <paramref name="openBehaviorType"/> is null.</exception>
41+
private static void ValidatePipelineBehaviorType(Type openBehaviorType)
42+
{
43+
if (openBehaviorType == null) throw new ArgumentNullException($"Open behavior type can not be null.");
44+
45+
bool isPipelineBehavior = openBehaviorType.GetInterfaces()
46+
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPipelineBehavior<,>));
47+
48+
if (!isPipelineBehavior)
49+
{
50+
throw new InvalidOperationException($"The type \"{openBehaviorType.Name}\" must implement IPipelineBehavior<,> interface.");
51+
}
52+
}
2053
}

0 commit comments

Comments
 (0)