具有多个构造函数的ASP.NET核心依赖项注入 [英] ASP.NET Core Dependency Injection with Multiple Constructors

查看:204
本文介绍了具有多个构造函数的ASP.NET核心依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET Core应用程序中有一个带有多个构造函数的标记助手.当ASP.NET 5尝试解析类型时,这会在运行时导致以下错误:

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:

InvalidOperationException:在"MyNameSpace.MyTagHelper"类型中找到了接受所有给定参数类型的多个构造函数.应该只有一个适用的构造函数.

InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'MyNameSpace.MyTagHelper'. There should only be one applicable constructor.

其中一个构造函数是无参数的,而另一个则具有一些其参数不是已注册类型的参数.我希望它使用无参数构造函数.

One of the constructors is parameterless and the other has some arguments whose parameters are not registered types. I would like it to use the parameterless constructor.

是否有某种方法可以获取ASP.NET 5依赖项注入框架来选择特定的构造函数?通常,这是通过使用属性来完成的,但是我什么也找不到.

Is there some way to get the ASP.NET 5 dependency injection framework to select a particular constructor? Usually this is done through the use of an attribute but I can't find anything.

我的用例是,我试图创建一个既是TagHelper,又是HTML Helper的单个类,如果解决此问题,这是完全可能的.

My use case is that I'm trying to create a single class that is both a TagHelper, as well as a HTML helper which is totally possible if this problem is solved.

推荐答案

Illya是正确的:内置解析器不支持公开多个构造函数的类型...但是没有什么可以阻止您注册一个代理来支持这种情况:

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<IService>(provider => {
    var dependency = provider.GetRequiredService<IDependency>();

    // You can select the constructor you want here.
    return new Service(dependency, "my string parameter");
});

注意:在更高版本中添加了对多个构造函数的支持,如其他答案所示.现在,DI堆栈将很乐意选择具有最多可解析参数的构造函数.例如,如果您有2个构造函数-一个构造函数带有3个指向服务的参数,另一个构造函数带有4个指向服务的构造器,则它将首选具有4个参数的一个.

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.

这篇关于具有多个构造函数的ASP.NET核心依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆