繁体   English   中英

使用具体类作为Controller属性.NET Core时获取InvalidOperationException

[英]Getting an InvalidOperationException when using a concrete class as a Controller property .NET Core

当将MailService传递给控制器​​的构造函数时,我的应用程序抛出System.InvalidOperationException 但是,当我将其切换为接口时,它可以工作。 这是什么原因呢?

Startup.cs

services.AddScoped<IMailService, MailService>();

在我的Controller

private IMailService MailService { get; }

public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, MailService mailService)
{
    if (userManager == null)
        throw new ArgumentNullException(nameof(userManager));

    if (signInManager == null)
        throw new ArgumentNullException(nameof(signInManager));

    if (mailService == null)
        throw new ArgumentNullException(nameof(mailService));

    this.UserManager = userManager;
    this.SignInManager = signInManager;
    this.MailService= mailService;
}

非常感谢!

services.AddScoped<IMailService, MailService>();

因为那条线。 您要告诉DI服务在IMailService类型的构造函数中遇到参数时,将其注入构造函数中的MailService实例。

您没有为注入(替换) MailService类型的实例定义任何内容。

您现在拥有的是好的做法,请不要更改它。 您希望在可能的情况下针对接口进行编程。 这也称为基于接口的编程 ,有很多好处。


另请参见一个可能相关的问题: “对接口进行编程”是什么意思?

我也注意到了这一点。 回到我们使用Unity for DI时,即使您没有专门将其添加到容器中,也可以通过解析您所请求的具体类来解决。

使用.NET Core依赖项注入,它要求您专门声明要注入的服务。 即使它可以解决您的具体课程,但我猜这个决定是在开发过程中的某个时候做出的,需要这样做。 因此,如果执行以下操作,您的代码将起作用:

services.AddScoped<MailService>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM