Skip to content

Commit

Permalink
Add configurable behaviors to MinimalApiMediatR
Browse files Browse the repository at this point in the history
  • Loading branch information
KrzysztofPajak committed Oct 19, 2024
1 parent 5559a3c commit d88dd2c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace MediatR.MinimalApi.Configurations;

public class MinimalApiMediatRConfiguration
{
public bool UseValidationBehavior { get; set; } = true;
public bool UseAuthorizationBehavior { get; set; } = true;
public bool UseRoleBasedPostProcessor { get; set; } = true;
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
using MediatR.MinimalApi.Behaviors;
using MediatR.MinimalApi.Configurations;
using MediatR.Pipeline;
using Microsoft.Extensions.DependencyInjection;

namespace MediatR.MinimalApi.Extensions;

public static class ServiceConfigurationExtensions
{
public static IServiceCollection MinimalApiMediatRExtensions(this IServiceCollection services)
public static IServiceCollection MinimalApiMediatRExtensions(this IServiceCollection services, Action<MinimalApiMediatRConfiguration> configure)
{
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehavior<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));
services.AddTransient(typeof(IRequestPostProcessor<,>), typeof(RoleBasedPostProcessor<,>));
var configuration = new MinimalApiMediatRConfiguration();
configure(configuration);

var registrationActions = new List<Action>
{
() => { if (configuration.UseValidationBehavior) services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); },
() => { if (configuration.UseAuthorizationBehavior) services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehavior<,>)); },
() => { if (configuration.UseRoleBasedPostProcessor) {
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));
services.AddTransient(typeof(IRequestPostProcessor<,>), typeof(RoleBasedPostProcessor<,>)); }
}
};

registrationActions.ForEach(action => action());

services.AddHttpContextAccessor();
return services;
Expand Down

0 comments on commit d88dd2c

Please sign in to comment.