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

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

问题描述

我的 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 Core 依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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