.NET Core DI, ways of passing parameters to constructor

后端 未结 3 1084
刺人心
刺人心 2020-12-02 08:28

Having the following service constructor

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


        
3条回答
  •  臣服心动
    2020-12-02 08:51

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

    Use that to resolve the dependencies,

    _serviceCollection.AddSingleton(x => 
        new Service(x.GetRequiredService(),
                    x.GetRequiredService(), 
                    ""));
    

    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.

提交回复
热议问题