Skip to content

Commit

Permalink
Add open behavior type must implement IPipelineBehavior interface rul…
Browse files Browse the repository at this point in the history
…e and some refactor with summaries.
  • Loading branch information
Emopusta committed Oct 1, 2024
1 parent 0d3bf4c commit e035b3f
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions src/MediatR/Entities/OpenBehavior.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,53 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace MediatR.Entities;
/// <summary>
/// Creates open behavior entity.
/// Represents a registration entity for pipeline behaviors with a specified service lifetime.
/// </summary>
public class OpenBehavior
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenBehavior"/> class.
/// </summary>
/// <param name="openBehaviorType">The type of the pipeline behavior to register.</param>
/// <param name="serviceLifetime">The lifetime of the registered service. Defaults to Transient.</param>
/// <exception cref="InvalidOperationException">Thrown if the specified type does not implement IPipelineBehavior.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="openBehaviorType"/> is null.</exception>
public OpenBehavior(Type openBehaviorType, ServiceLifetime serviceLifetime = ServiceLifetime.Transient)
{
ValidatePipelineBehaviorType(openBehaviorType);
OpenBehaviorType = openBehaviorType;
ServiceLifetime = serviceLifetime;
}

public Type? OpenBehaviorType { get; }
/// <summary>
/// The type of the open behavior.
/// </summary>
public Type OpenBehaviorType { get; }

/// <summary>
/// The service lifetime of the open behavior.
/// </summary>
public ServiceLifetime ServiceLifetime { get; }


/// <summary>
/// Validates whether the specified type implements the <see cref="IPipelineBehavior{TRequest, TResponse}"/> interface.
/// </summary>
/// <param name="openBehaviorType">The type to validate.</param>
/// <exception cref="InvalidOperationException">Thrown if the type does not implement <see cref="IPipelineBehavior{TRequest, TResponse}"/>.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="openBehaviorType"/> is null.</exception>
private static void ValidatePipelineBehaviorType(Type openBehaviorType)
{
if (openBehaviorType == null) throw new ArgumentNullException(nameof(openBehaviorType));

bool isPipelineBehavior = openBehaviorType.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IPipelineBehavior<,>));

if (!isPipelineBehavior)
{
throw new InvalidOperationException($"The type \"{openBehaviorType.Name}\" must implement IPipelineBehavior<,> interface.");
}
}
}

0 comments on commit e035b3f

Please sign in to comment.