Looking to get some advice/information on Blazor best practice when an injected service depends on another service.
I'm going to use the standard Blazor server template provided by Microsoft as an example. I create my test project with dotnet new blazorserver
Suppose my WeatherForecastService
class depends on an external data service IDataService
for data. My interface is defined as follows:
public interface IDataService
{
public string GetData();
}
and a concrete class that I'll use as a service is defined as
public class DataService : IDataService
{
public string GetData()
{
//any implementation would communicate with an external service
return "Some Data Here";
}
}
To use IDataService
in WeatherForecastService
I've thought of two ways of using the service.
Option 1 - inject the dependency as part of method definitions
I could inject the dependency into wherever it's needed. For example if I added a GetDataFromDataService
method to WeatherForecastService
it might look as follows:
public string GetDataFromDataService(IDataService service)
{
return service.GetData();
}
Benefits
- Registering the service is easy via Program.fs i.e.
builder.Services.AddSingleton<IDataService>(new DataService());
- This service is available to other services that might need it.
Drawbacks
- every method that needs this service needs the service passed in as a parameter (could get messy)
- every component that requires
WeatherForecastService
injected will likely need a second service injected as well.
Option 2 - inject the dependency as part of the class constructor
As an alternative, one could inject the service as part of the WeatherForecastService
constructor e.g.
private IDataService service { get; }
public WeatherForecastService(IDataService service)
{
this.service = service;
}
public string GetDataFromDataService()
{
return service.GetData();
}
Benefits
- service passed in once. Can be reused several times.
Drawbacks
- service wouldn't be available for other services
- depending on how complex a constructor is, you may find yourself doing the following in
Program.fs
which just feels wrong.
var dataService = new DataService();
builder.Services.AddSingleton(new WeatherForecastService(dataService));
Conclusion
I've listed the above options as they're the ones I've thought of so far - are there any I'm missing? Additionally, is there a best practice around this or is it a case of "it depends"?
Many thanks for any advice on this!