Multiple Constructors Service
In some rare cases, you will need to create a multiple constructors dependency injection service. This guide will walk you through on how to create a multiple constructor service and how to inject them accordingly.
You can download the example code used in this topic on GitHub.
Creating the service class
The service class will have multiple constructors. Refer to the MutipleConstructorsService
class in our example.
public class MutipleConstructorsService : IFirstConstructor, ISecondConstructor
{
public string ServiceDetail { get; }
public MutipleConstructorsService(SimpleService simpleService) => ServiceDetail = "Constructed with first constructor";
public MutipleConstructorsService(NestedService nestedService) => ServiceDetail = "Constructed with second constructor";
}
In this example, we have 2 constructors. Each constructor will change the value ServiceDetail
accordingly. We will use this service class to inject to a component later on and check the value of ServiceDetail
to see which constructor being called.
Creating the interface
For each of the constructors you created in the service class, you will to declare an interface for it. Blazor WebAssembly distinguishes them by the interface. In our example, we have 2 interfaces for 2 constructors of the class MutipleConstructorsService
.
public interface IFirstConstructor
{
string ServiceDetail { get; }
}
public interface ISecondConstructor
{
string ServiceDetail { get; }
}
Registering the service
The next step would be to register the service at Startup.cs
. You need to use the interface to register your service.
builder.Services.AddSingleton<IFirstConstructor, MutipleConstructorsService>(sp => new(sp.GetRequiredService<SimpleService>()));
builder.Services.AddSingleton<ISecondConstructor, MutipleConstructorsService>(sp => new(sp.GetRequiredService<NestedService>()));
Injecting the service
Since you registered the service by its interface, you will need to use the interface to inject your service into a component.
@inject IFirstConstructor ConstructedWithFirstConstructor
@inject ISecondConstructor ConstructedWithSecondConstructor
<h3>@ConstructedWithFirstConstructor.ServiceDetail</h3>
<h3>@ConstructedWithSecondConstructor.ServiceDetail</h3>
You will see the result as the follow image.