Search code examples
c#asp.net-core-7.0brighter

How do you configure Brighter with ASP.NET Core 7?


How do you configure Brighter with ASP.NET Core 7? Brighter documentation is pretty sparse on details, sample on the internet seems outdated too.

Is there sample startup code (Program.cs) and a basic Controller available on the web?


Solution

  • I got it to work, here is a sample code.

    using Paramore.Brighter;
    using Paramore.Brighter.Extensions.DependencyInjection;
    using Polly;
    using Polly.Registry;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    builder.Services
        .AddBrighter(options =>
        {
            var retryPolicy = Policy.Handle<Exception>().WaitAndRetry(new[]
            {
                TimeSpan.FromMilliseconds(50),
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(200)
            });
    
            var circuitBreakerPolicy = Policy.Handle<Exception>().CircuitBreaker(2,
                TimeSpan.FromMilliseconds(500));
    
            var retryPolicyAsync = Policy.Handle<Exception>()
                .WaitAndRetryAsync(new[]
                    { TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(200) });
    
            var circuitBreakerPolicyAsync =
                Policy.Handle<Exception>().CircuitBreakerAsync(2, TimeSpan.FromMilliseconds(500));
    
            options.PolicyRegistry = new PolicyRegistry
            {
                { CommandProcessor.RETRYPOLICY, retryPolicy },
                { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy },
                { CommandProcessor.RETRYPOLICYASYNC, retryPolicyAsync },
                { CommandProcessor.CIRCUITBREAKERASYNC, circuitBreakerPolicyAsync }
            };
    
            options.HandlerLifetime = ServiceLifetime.Scoped;
            options.CommandProcessorLifetime = ServiceLifetime.Scoped;
            options.MapperLifetime = ServiceLifetime.Singleton;
        })
        .AutoFromAssemblies(typeof(MyService).Assembly);
    
    
    builder.Services.AddScoped<MyService>();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    
    public partial class Program
    {
    }