Named service

Named services are used when you have multiple instances of the same implementation and decide which instance to use during runtime. A named service is using a factory that decides which implementation should be returned. The service type for a named service needs to be an interface or abstract class.

In Litium the payment provider is an example of an implementation that uses the named services. Each payment provider is registered with the payment provider name in the dependency engine and is later accessible as a named service.

Example of named service registration:

[Litium.Runtime.DependencyInjection.Service(
    ServiceType = typeof(IMyService),
    Lifetime = Litium.Runtime.DependencyInjection.DependencyLifetime.Transient,
    NamedService = true)]
public interface IMyService
{
    void MyMethod(); // define the service contract members
}

[Service(Name = "Service1")]
internal class MyServiceImpl1 : IMyService
{
    public void MyMethod()
    {
        // do something in the method
    }
}

[Service(Name = "Service2")]
internal class MyServiceImpl2 : IMyService
{
    public void MyMethod()
    {
        // do something in the method
    }
}

Example of usage of the named service registration:

internal class NamedDependencyUsage
{
    private readonly IMyService _myService;

    public NamedDependencyUsage(IServiceProvider serviceProvider, AuthorizationService authorizationService)
    {
        _myService = serviceProvider.GetRequiredNamedService<IMyService>(
            authorizationService.HasOperation("MyOperation")
                ? "Service1"
                : "Service2");
    }

    public void Method()
    {
        _myService.MyMethod();
    }
}

 

 

 

 

Is this page helpful?
Thank you for your feedback!