|
| 1 | +using CleanArchitecture.Extensions.Exceptions.Behaviors; |
| 2 | +using CleanArchitecture.Extensions.Exceptions.Catalog; |
| 3 | +using CleanArchitecture.Extensions.Exceptions.Options; |
| 4 | +using CleanArchitecture.Extensions.Exceptions.Redaction; |
| 5 | +using MediatR; |
| 6 | +using Microsoft.Extensions.DependencyInjection; |
| 7 | +using Microsoft.Extensions.DependencyInjection.Extensions; |
| 8 | + |
| 9 | +namespace CleanArchitecture.Extensions.Exceptions; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// Registration helpers for CleanArchitecture.Extensions.Exceptions. |
| 13 | +/// </summary> |
| 14 | +public static class DependencyInjectionExtensions |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// Registers exception handling services (catalog, redactor, options). |
| 18 | + /// </summary> |
| 19 | + /// <param name="services">Service collection.</param> |
| 20 | + /// <param name="configureHandling">Optional callback to configure <see cref="ExceptionHandlingOptions"/>.</param> |
| 21 | + /// <param name="configureCatalog">Optional callback to configure <see cref="ExceptionCatalogOptions"/>.</param> |
| 22 | + public static IServiceCollection AddCleanArchitectureExceptions( |
| 23 | + this IServiceCollection services, |
| 24 | + Action<ExceptionHandlingOptions>? configureHandling = null, |
| 25 | + Action<ExceptionCatalogOptions>? configureCatalog = null) |
| 26 | + { |
| 27 | + ArgumentNullException.ThrowIfNull(services); |
| 28 | + |
| 29 | + var handlingBuilder = services.AddOptions<ExceptionHandlingOptions>(); |
| 30 | + if (configureHandling is not null) |
| 31 | + { |
| 32 | + handlingBuilder.Configure(configureHandling); |
| 33 | + } |
| 34 | + |
| 35 | + var catalogBuilder = services.AddOptions<ExceptionCatalogOptions>(); |
| 36 | + if (configureCatalog is not null) |
| 37 | + { |
| 38 | + catalogBuilder.Configure(configureCatalog); |
| 39 | + } |
| 40 | + |
| 41 | + services.TryAddSingleton<IExceptionCatalog, ExceptionCatalog>(); |
| 42 | + services.TryAddSingleton<ExceptionRedactor>(); |
| 43 | + |
| 44 | + return services; |
| 45 | + } |
| 46 | + |
| 47 | + /// <summary> |
| 48 | + /// Adds the MediatR exception wrapping behavior to the pipeline. |
| 49 | + /// </summary> |
| 50 | + public static MediatRServiceConfiguration AddCleanArchitectureExceptionsPipeline( |
| 51 | + this MediatRServiceConfiguration configuration) |
| 52 | + { |
| 53 | + ArgumentNullException.ThrowIfNull(configuration); |
| 54 | + |
| 55 | + configuration.AddOpenBehavior(typeof(ExceptionWrappingBehavior<,>)); |
| 56 | + return configuration; |
| 57 | + } |
| 58 | +} |
0 commit comments