Fluxor icon indicating copy to clipboard operation
Fluxor copied to clipboard

Is there a way to use Fluxor with the new Blazor Web App paradigm? .NET8.0

Open Rhywden opened this issue 1 year ago • 37 comments

Now with .NET8 released into production we also have what was formerly called Blazor United, i.e. where there formerly was a strict distinction between Blazor Server and Blazor WASM we now have both in one application.

Problem is that I cannot quite figure out how to get Fluxor to get to work on the "client side". For example, App.razor simply does not exist anymore, only on the "server". This here does not work: client/Program.cs

[...]
var currentAssembly = typeof(Program).Assembly;
builder.Services.AddFluxor(options => options.ScanAssemblies(currentAssembly).UseReduxDevTools());
[...]

client/Pages/Counter.razor

@page "/counter"
@rendermode InteractiveAuto

<Fluxor.Blazor.Web.StoreInitializer />

<PageTitle>Counter</PageTitle>

which yields: InvalidOperationException: Cannot provide a value for property 'Store' on type 'Fluxor.Blazor.Web.StoreInitializer'. There is no registered service of type 'Fluxor.IStore'.

Changing to InteractiveWebAssembly does not change anything about that.

So, is there a way forward?

Rhywden avatar Nov 14 '23 21:11 Rhywden

Okay, so I found a way to get things going. Works like this: You define your actions, state and reducers completely like normal on the Client. Then you create a static method to register your Fluxor service on the Client:

public static class CommonServices
{
    public static void ConfigureServices(IServiceCollection services)
    {
        var currentAssembly = typeof(Program).Assembly;
        services.AddFluxor(options => options.ScanAssemblies(currentAssembly).UseReduxDevTools());
    }
}

You call this method in Client/Program.cs like so:

var builder = WebAssemblyHostBuilder.CreateDefault(args);

CommonServices.ConfigureServices(builder.Services);

await builder.Build().RunAsync();

and also on the Server like so:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents()
    .AddInteractiveWebAssemblyComponents();

YourBlazorWebApp.Client.CommonServices.ConfigureServices(builder.Services);

I didn't find a good place to initialize the store yet. Currently it only gets initialized the first time you hit a Client-side page (like the Counter from the default template):

@page "/counter"
@using YourBlazorWebApp.Client.Store.CounterUseCase
@using Fluxor
@rendermode InteractiveAuto
@inherits Fluxor.Blazor.Web.Components.FluxorComponent

<Fluxor.Blazor.Web.StoreInitializer />

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @CounterState?.Value.ClickCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    [Inject]
    private IState<CounterState>? CounterState { get; set; }
    [Inject]
    public IDispatcher? Dispatcher { get; set; }

    private void IncrementCount()
    {
        var action = new IncrementCounterAction();
        Dispatcher?.Dispatch(action);
    }
}

but then it'll work and seemingly won't reinitialize every time you hit this page. The store also doesn't get destroyed if you navigate away.

But registering the service on both sides is essential!

Rhywden avatar Nov 15 '23 10:11 Rhywden

Can confirm I get this same error on a clean .Net 8 webassembly app with a simple Fluxor state.

InvalidOperationException: Cannot provide a value for property 'Store' on type 'Fluxor.Blazor.Web.StoreInitializer'. There is no registered service of type 'Fluxor.IStore'.

Program.cs

builder.Services.AddScoped<TenantsState>();

builder.Services.AddFluxor(options =>
{
    options.ScanAssemblies(typeof(Program).Assembly);
    options.UseReduxDevTools(rdt =>
    {
        rdt.Name = "Backend.Client";
    });
});

Routes.razor

<Fluxor.Blazor.Web.StoreInitializer />
<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
</Router>

Home.razor

@page "/"
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@inject IState<TenantsState> _tenantsState

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

@_tenantsState.Value.SelectedTenant

two-thirty-seven avatar Nov 16 '23 18:11 two-thirty-seven

Interestingly...... I just converted my static web app WebAssembly application to .Net 8 and Fluxor had no issues. So maybe it's some conflict with the hosted model?

two-thirty-seven avatar Nov 17 '23 21:11 two-thirty-seven

@Rhywden When you add Fluxor to your services in the server project, the ScanAssemblies method has an overload that allows you to include additional assemblies so you can reference the Client assembly.

builder.Services.AddFluxor(o => o
      .ScanAssemblies(typeof(Program).Assembly, new[] { typeof(Client._Imports).Assembly }));

I have also not found a way to initialize the store so for now I am also placing the initializer on any client side page that uses Fluxor in the same manner as you are doing.

stagep avatar Nov 17 '23 21:11 stagep

One way to initialize the client side store is to add a component in your client project that contains

@rendermode InteractiveWebAssembly
<Fluxor.Blazor.Web.StoreInitializer />

and then add this component to your main layout page in the server project.

stagep avatar Nov 17 '23 23:11 stagep

One way to initialize the client side store is to add a component in your client project that contains

@rendermode InteractiveWebAssembly
<Fluxor.Blazor.Web.StoreInitializer />

and then add this component to your main layout page in the server project.

The default @rendermode InteractiveAuto works just fine. But yes, putting it somewhere that only gets loaded once (like a Navbar or an Appbar) is a good spot to put it. I also put the initializers for Mudblazor there so I can get Dialogs / Modals / Snackbar.

Rhywden avatar Nov 19 '23 23:11 Rhywden

Okay, so I found a way to get things going. Works like this: You define your actions, state and reducers completely like normal on the Client.

But registering the service on both sides is essential!

This would scan with the official docs on DI:

https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/dependency-injection?view=aspnetcore-8.0#register-common-services

two-thirty-seven avatar Nov 23 '23 09:11 two-thirty-seven

Yes, that's where I got it from.

Rhywden avatar Nov 23 '23 10:11 Rhywden

Having the same problem but still struggling with following the above suggestions. Does anyone have a minimal implementation they could share?

AndreaEBM avatar Nov 30 '23 14:11 AndreaEBM

Please tell us what options you selected for Interactive render mode and Interactivity location when creating the project(s).

stagep avatar Nov 30 '23 18:11 stagep

Please tell us what options you selected for Interactive render mode and Interactivity location when creating the project(s).

Auto and (is this my issue?) per page/component

AndreaEBM avatar Dec 01 '23 10:12 AndreaEBM

Do the components using Fluxor exist only in the Client (WebAssembly) project?

stagep avatar Dec 02 '23 00:12 stagep

I have created a sample application that demonstrates Fluxor working in the client (WASM) successfully with a client counter. The application also includes a server side counter that does not work consistently, and if it does work, the client side counter will not work.

Link

stagep avatar Dec 03 '23 03:12 stagep

s using Fluxor exist only i

Thank you so much. Your solution works for me, but copying across into my solution doesn't work. I think I must have other issues to resolve as part of my .net8 migraion. I will continue hunting.

AndreaEBM avatar Dec 05 '23 14:12 AndreaEBM

Are you talking about the new "static server side rendering"?

If so, that's a stateless approach. The state of the page is determined on every render, so you don't need local state.

mrpmorris avatar Dec 06 '23 08:12 mrpmorris

Are you talking about the new "static server side rendering"?

If so, that's a stateless approach. The state of the page is determined on every render, so you don't need local state.

Yes, but the original issue was on how to get it working at all. We found out but the docs might need an update.

Rhywden avatar Dec 06 '23 09:12 Rhywden

@mrpmorris The example that I put on Github is using InteractiveServer and InteractiveWebAssembly rendering to represent a stateful application on both the server and the client. This example will only work with one of these render modes, and the server rendered counter does not always work. Please try the example to see this.

https://github.com/stagep/Blazor8WithFluxor

stagep avatar Dec 07 '23 00:12 stagep

Isn't asking how to get a state library to work on a stateless architecture like asking where to put the petrol in a solar panel?

They are different things.

mrpmorris avatar Dec 12 '23 12:12 mrpmorris

InteractiveServer render mode is not stateless.

ASP.NET Core Blazor state management

stagep avatar Dec 12 '23 16:12 stagep

@mrpmorris Did you have a chance to look at my stateful server and client application? It seems that the Fluxor library will only work with either InteractiveServer or InteractiveWebAssembly rendering.

stagep avatar Dec 20 '23 22:12 stagep

So I had to register my fluxor and other services on both client and server. However, my stores are only on the client as I do not intend on using them ons server currently, or Ill move them to a shared library and register them that way.

However, I also required making the StoreInitializer on the Routes, utilize the InteractiveServer rendermode as it was running as static and thus, no functionality.

<Fluxor.Blazor.Web.StoreInitializer @rendermode="InteractiveServer" />

Hope that Helps

SethVanderZanden avatar Dec 29 '23 20:12 SethVanderZanden

It looks like the Store can only be initialized once, either WASM or Server. If InteractiveAuto is used and only InteractiveServer pages are used, the store is initialized as InteractiveServer and then InteractiveAuto components can't use the store. If only InteractiveWebAssembly pages are used the store is initialized as InteractiveWebAssembly and then InteractiveServer pages don't work.

It seems like some work is required to initialize the store once but in a way that both WASM and Server components can use it.

pjh1974 avatar Jan 03 '24 12:01 pjh1974

It seems like some work is required to initialize the store once but in a way that both WASM and Server components can use it.

Just to make it clear: Even if both sides (server and client) can initialize a store, they'll be decoupled and completely independent of each other.

Rhywden avatar Jan 03 '24 13:01 Rhywden

It looks like the Store can only be initialized once, either WASM or Server. If InteractiveAuto is used and only InteractiveServer pages are used, the store is initialized as InteractiveServer and then InteractiveAuto components can't use the store. If only InteractiveWebAssembly pages are used the store is initialized as InteractiveWebAssembly and then InteractiveServer pages don't work.

It seems like some work is required to initialize the store once but in a way that both WASM and Server components can use it.

I have registered the services on both server and client, however the store has had no issues with interactive auto. The initial load uses server, subsequent loads use the DLL. If you refresh the page the state is always lost, which is normal Fluxor behaviour.

SethVanderZanden avatar Jan 03 '24 15:01 SethVanderZanden

I don't think InteractiveAuto actually works, see the following link:

https://github.com/dotnet/aspnetcore/issues/52154

All my tests show that it just does pre-rendering. I'm not sure if this affects the use of the <Fluxor.Blazor.Web.StoreInitializer /> component or not though.

In my tests I'm going with the @Rhywden suggestion of using the store initializer from a component in the client project with interactive auto rendering but it only initializes once, either on the server or the client. @SethVanderZanden how are you initializing the store if you have it working in both places?

pjh1974 avatar Jan 03 '24 16:01 pjh1974

It looks like the Store can only be initialized once, either WASM or Server. If InteractiveAuto is used and only InteractiveServer pages are used, the store is initialized as InteractiveServer and then InteractiveAuto components can't use the store. If only InteractiveWebAssembly pages are used the store is initialized as InteractiveWebAssembly and then InteractiveServer pages don't work. It seems like some work is required to initialize the store once but in a way that both WASM and Server components can use it.

I have registered the services on both server and client, however the store has had no issues with interactive auto. The initial load uses server, subsequent loads use the DLL. If you refresh the page the state is always lost, which is normal Fluxor behaviour.

This would mean that InteractiveAuto (if it actually worked) wouldn't really work well with Fluxor. The page would load by fetching data from a server side store and then any interactivity on the page would then be handed off to WASM, which would be a different store, so the state would be different.

I see limited uses for InteractiveAuto anyway, so I wouldn't say this was a "show-stopper".

pjh1974 avatar Jan 03 '24 16:01 pjh1974

I don't think InteractiveAuto actually works, see the following link:

https://github.com/dotnet/aspnetcore/issues/52154

All my tests show that it just does pre-rendering. I'm not sure if this affects the use of the <Fluxor.Blazor.Web.StoreInitializer /> component or not though.

In my tests I'm going with the @Rhywden suggestion of using the store initializer from a component in the client project with interactive auto rendering but it only initializes once, either on the server or the client. @SethVanderZanden how are you initializing the store if you have it working in both places?

In routes.razor w rendermode as InteractiveServer. The base functionality will work fine for InteractiveAuto. The base functionality of Fluxor works the same on both interactiveserver and interactivewebassembly to my knowledge, correct me if I'm wrong. Just like in the past I don't recall setting up Fluxor differently or having 2 different set of code to work on Server or WebAssembly, they all store state within the tab and is lost on refresh no matter the rendering method.

SethVanderZanden avatar Jan 03 '24 16:01 SethVanderZanden

I updated my sample. Counters on both Server and WebAssembly work. State will be lost on the Server counters once you switch to using only WebAssembly as the connection to the server is cleaned up (this is to be expected). There are 2 separate Server counters (Server Counter and Server Double Counter) that you can switch between and see that they maintain state. A couple of points:

  • Prerendering on WebAssembly cannot be used
  • StoreInitializer is required on every interactive page

https://github.com/stagep/Blazor8WithFluxor

stagep avatar Jan 03 '24 18:01 stagep

It looks like the Store can only be initialized once, either WASM or Server. If InteractiveAuto is used and only InteractiveServer pages are used, the store is initialized as InteractiveServer and then InteractiveAuto components can't use the store. If only InteractiveWebAssembly pages are used the store is initialized as InteractiveWebAssembly and then InteractiveServer pages don't work.

It seems like some work is required to initialize the store once but in a way that both WASM and Server components can use it.

I'm facing the same issue as above.

orosbogdan avatar Feb 16 '24 22:02 orosbogdan

@mrpmorris can you elaborate? The question is how can we get fluxor to work with the new blazor web app template. In this template there is a server project and a client project. I would like to manage client state with fluxor in the client project.

Oringally there was an App.razor file in the client project of the old templates. With the new template there is no App.razor file, and no mention in the documentation on where to place <Fluxor.Blazor.Web.StoreInitializer /> in the new blazor web app template. Placing it on every page does not seem like a sustainable or maintainable solution.

Is it that the new template is simply not supported at this time?

janusqa avatar Feb 27 '24 00:02 janusqa