【问题标题】:Getting an InvalidOperationException when using a concrete class as a Controller property .NET Core使用具体类作为控制器属性 .NET Core 时获取 InvalidOperationException
【发布时间】:2017-10-25 11:26:43
【问题描述】:

当将MailService 传递给我的Controller 的构造函数时,我的应用程序会抛出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;
}

非常感谢!

【问题讨论】:

  • 您的代码(编辑后)看起来不错,因此最好提供确切的错误消息和堆栈跟踪的顶部。

标签: c# asp.net dependency-injection asp.net-core


【解决方案1】:
services.AddScoped<IMailService, MailService>();

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

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

你现在的做法是好的,不要改变它。您希望尽可能针对接口进行编程。这也称为interface based programming,有很多好处。


另请参阅可能相关的问题:What does it mean to "program to an interface"?

【讨论】:

  • 我后来意识到/学到了这一点!澄清一下,你是说我要求的是服务而不是接口,所以当我要求 IMailService 时,DI 容器只是设置为给我一个 MailService?
【解决方案2】:

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

使用 .NET Core 依赖注入,它要求您明确声明要注入的服务。尽管它可以解决您的具体课程,但我猜想在开发过程中的某个时刻做出了需要这样做的决定。因此,如果您这样做,您的代码将起作用:

services.AddScoped<MailService>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多