.NET Core DI, ways of passing parameters to constructor

The expression parameter (x in this case) of the factory delegate is an 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. Whenever the type is to be resolved, it will pass the completed provider as the delegate parameter.

Leave a Comment