mrpmorris / Fluxor

Fluxor is a zero boilerplate Flux/Redux library for Microsoft .NET and Blazor.
MIT License
1.28k stars 147 forks source link

Question: Fluxor + DelegatingHandler in Blazor WASM #180

Closed Pjotrtje closed 3 years ago

Pjotrtje commented 3 years ago

Hello, I have a question related to Fluxor + DelegatingHandler for HttpClientFactory. I want to access Fluxor to determine some header values for a request. But when I provide state in constructor I get a different state than the rest in my Blazor app.

Apparently DelegatingHandler registered with AddHttpMessageHandler are singletons in a pool or something. And Fluxor is scoped. Right? So we get a scoping mismatch (assumption) resulting in 2 states.

The workaround for server app seems to inject IHttpContextAccessor. And do something like this:

internal class HeadersHandler: DelegatingHandler
{
    private readonly IHttpContextAccessor httpContextAccessor;

    protected HeadersHandler(IHttpContextAccessor httpContextAccessor)
    {
        this.httpContextAccessor = httpContextAccessor;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var serviceProvider = this.httpContextAccessor.HttpContext.RequestServices;
        var state = serviceProvider.GetRequiredService<IState<SettingsState>>();
        ...
    }
}

But IHttpContextAccessor seems not avalable for Blazor WASM. So now my workaround is:

internal sealed class HeadersHandler : DelegatingHandler
{
    public static IState<SettingsState> State { get; set; }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        ...
    }       
}

and then in MainLayout do

[Inject]
private IState<SettingsState> State { get; set; } 

protected override void OnInitialized()
{
    HeadersHandler.Sate = this.State ;
}

Which works, but is kinda ugly. For Blazor WASM Scope=Singleton in theory. Rite? So I think when registering Fluxor as Singleton I can just do dependency injection in constructor?

My questions: 1) Are you familiar with this issue? (Or do you not have this problem and am I doing something wrong?) 2) If my descriptions and issue are real. Then I guess my feature request is the posibility to register Fluxor as Singleton for Blazor WASM.

My workaround is doable by the way. But it is ugly, so if I make it more neat I would be happy. Love to hear what you think.

mrpmorris commented 3 years ago

If you create a scoped service for issuing your http calls then it can create a http request and set the headers before calling.