.NET Core DI, ways of passing parameters to constructor

boris picture boris · Dec 21, 2018 · Viewed 64.6k times · Source

Having the following service constructor

public class Service : IService
{
     public Service(IOtherService service1, IAnotherOne service2, string arg)
     {

     }
}

What are the choices of passing the parameters using .NET Core IOC mechanism

_serviceCollection.AddSingleton<IOtherService , OtherService>();
_serviceCollection.AddSingleton<IAnotherOne , AnotherOne>();
_serviceCollection.AddSingleton<IService>(x=>new Service( _serviceCollection.BuildServiceProvider().GetService<IOtherService>(), _serviceCollection.BuildServiceProvider().GetService<IAnotherOne >(), "" ));

Is there any other way ?

Answer

Nkosi picture Nkosi · Dec 21, 2018

The expression parameter (x in this case), of the factory delegate is a IServiceProvider.

Use that to resolve the dependencies,

_serviceCollection.AddSingleton<IService>(x => 
    new Service(x.GetRequiredService<IOtherService>(),
                x.GetRequiredService<IAnotherOne>(), 
                ""));

The factory delegate is a delayed invocation. When ever the type is to be resolved it will pass the completed provider as the delegate parameter.