Reputation: 328
In Blazor with .net 7, using hosted WebAssembly I have to call a webapi creating a controller on the server side that responds to the request.
With the new Blazor full stack approach of .net 8, if I want to use a InteractiveWebAssembly component it must be created in the client project, but it does not have access to the services of the main project. Should I still create a webApp in the main project and call it from the InteractiveWebAssembly component using http requests?
I created a page in the client project but I cannot inject a service from the main project.
Thanks for your help
Upvotes: 3
Views: 4234
Reputation: 1
I found a very useful solution in this video:
https://youtu.be/zv2gdqxZmFs?si=PKgEixDoP-7QX8Lg
It creates an additional project, a class library, and uses it for models and interfaces, then you can create a service folder on your client project that implements they interface, using dependency injection in your program.cs and inject an httpClient service, all this un the client project, so you can make API calls from your services. In the server project create another class that implements the same interface, this class will be in charge of communication with the data base using dapper I.E. and finally create a web API controller in your server side project that receives the responses from the class that communicates with the database. With this approach you only need to create 1 global interface that will be implemented in both client and server projects, you will have an API controller to safely comunícate the database to your client project without exposing sensitive data and the freedom to use server or client side components as you wish.
Upvotes: 0
Reputation: 4957
Just like in .NET 7-, the Webassembly/Client project will be compiled and uploaded onto the users browser on its own. So it will be completely separated from the Server/Main project and require it's own services.
To quote MS docs
Components rendered for the Blazor Server hosting model have direct access to server and network resources where the app is executing. Because components hosted using Blazor WebAssembly or Blazor Hybrid execute on a client, they don't have direct access to server and network resources. Components can access server and network resources indirectly via protected server-based APIs. Server-based APIs might be available via third-party libraries, packages, and services.
Now with .NET 8, you have the option to either load your data/access server side services on a Webassembly/Client component using API calls or just make it a Server component and access it directly.
Upvotes: 2