dotnet / dotnet/aspnetcore

[Blazor] Simplify writing code that works across different environments

Open
#60,312 10 comments 5 reactions 0 assignees View on GitHub
area-blazor
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

Currently, when a component/service needs to run on the server and on webassembly, developers are forced to create at least two versions of the service, put each version in a different location depending on whether it runs on the server or on webassembly, and register things in the DI container twice.

This in many cases is hard to get right, as it requires several steps and it's easy to miss something.

As an alternative, we can consider bringing back multi-targeting support. With this approach, it should be possible for the app to define both implementations on the same location and use the same call to register the services in one go. We can update the template to support such pattern when webassembly is involved.

One such example is:

```csharp
#if !NET10_WASM
public class WeatherForecastService(WeatherContext context)
#else
public class WeatherForecastService(HttpClient ctx)
#endif

public async Task GetForecastAsync(Date ...)
{
#if !NET10_WASM
return _httpClient.Getasync<...>...
#else
return context.Forecasts.ToListAsync();
}
```

```csharp
public static class ServiceRegistrationExtensions
{
public static IServiceCollection AddCommonServices(this IServiceCollection services)
{
services.AddScoped();
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.