Search code examples
dbcontextblazoref-core-3.1webui

How to share DbContext between different WebApps?


I've one missing link to understood how it could work to "connect" my EF core's DbContext to different applications in following scenario:

I've got one application project which contains the whole EF Core Code first datamodel (Entities, Business Logic, Enums etc).

Until now we're using a WebAPI application to share data with multiple endpoints. So the data we're exchanging now are quite static at the moment. We create our DbContext and the API is using it for data reading and write operations.

Now there is customer request to also build a WebUI (Blazor). So we still want to use the WebAPI for data exchange in the UI, but further we need some more business logic elements from our data model (containing INotifyPropertyChanged event handling etc). We implemented the event handles in the entity classes. So we intend to build a session object for each user/client which contains the DbContext instance. But how can handover an instantiated DbContext from the Web API to my UI Application.

Would be nice to get some input. Thx for any advice.


Solution

  • You do not pass the DBContext object to "UI Application", such as a Blazor app. You did not mention what flavor of Blazor you are using... However, the following may be applicable for both Blazor Server App and Blazor WebAssembly App... From what I've gather from your question you are exposing Web Api end points to retrieve data and save data. This is good. What is left for you to do is to create code in your Blazor that access those end points. You should use the HttpClient service to do this. If you use Blazor client side, this object is configured and made available for injection in your components and services. This type of HttpClient is based on the JavaScript Fetch Api.

    If you are going to create a Balzor Server App, then you'll have to add the HttpClient service to the DI container and configure it accordingly, and only then you'd be able to inject it into your components and services. In this case you should use the IHttpClientFactory to provide the HttpClien onjects.

    In principle, you have to query your Web Api methods via HttpClient.

    Note that if you use Blazor Server App, you don't have to use Web Api. Instead you can create services that perform similar functionality to that provided by the Web Api.

    Please, go to the docs and acquaint yourself how to use the HttpClient with Blazor apps.

    Hope this helps...