ASP.NET Core Dependency Injection with Multiple Constructors

后端 未结 5 2063
独厮守ぢ
独厮守ぢ 2020-12-06 04:33

I have a tag helper with multiple constructors in my ASP.NET Core application. This causes the following error at runtime when ASP.NET 5 tries to resolve the type:

5条回答
  •  無奈伤痛
    2020-12-06 04:40

    Illya is right: the built-in resolver doesn't support types exposing multiple constructors... but nothing prevents you from registering a delegate to support this scenario:

    services.AddScoped(provider => {
        var dependency = provider.GetRequiredService();
    
        // You can select the constructor you want here.
        return new Service(dependency, "my string parameter");
    });
    

    Note: support for multiple constructors was added in later versions, as indicated in the other answers. Now, the DI stack will happily choose the constructor with the most parameters it can resolve. For instance, if you have 2 constructors - one with 3 parameters pointing to services and another one with 4 - it will prefer the one with 4 parameters.

提交回复
热议问题