Maui hybrid Desktop and a Web client share the same database
Changes to the WeatherForecastService
private bool hosted = false;public WeatherForecastService(bool isHosted){hosted = isHosted;}
Then in the GetForecastAsync method, we check the hosted value. if true, we call the API:
private async Task<WeatherForecast[]> APIManager()
{
HttpClient httpClient = new();
var result = await httpClient.GetFromJsonAsync<WeatherForecast[]>("https://localhost:7198/WeatherForecast");
if (result == null)
{
result = Array.Empty<WeatherForecast>();
}
return result;
}
It should be noted, this is the exact same method that is called for the Web client as well. This is another excellent example of how we are to reuse key components across different clients.
We need to make a change to MauiProgram.cs. We need to set the hosted flag before we inject the service.
bool hosted = true;
builder.Services.AddSingleton<WeatherForecastService>(sp => new WeatherForecastService(hosted));
We will need to add this code to the Web client program.cs as well.
At this point, we have the code we need to be sharing the data sources between the web client and the desktop client. But when we try to call the API from the desktop it fails. The usual error is the Server refused connection. This is caused because we have not turned on CORS in the API controller. There are plenty of good resources for enabling CORS in a Web API. Here is the link I used, C# Corner.
You just need to enable CORS so the desktop application can access the API. In a production environment, you would want to make sure the API service is secured.
Summary
We now have a system that can be deployed as a stand-alone Desktop application, a web application, or both. All sharing UI code and back-end service code. Very cool!
In this example, I am using a Web API for the back-end service. We can just as easily use Azure Functions, Redis Cache, or any other back-end service.
The new Maui technology really opened up the possible solutions I have been looking for over the last 10 years.
Comments
Post a Comment