[英]Getting an InvalidOperationException when using a concrete class as a Controller property .NET Core
When passing MailService
to my Controller's constructor my app throws a System.InvalidOperationException
. 当将MailService
传递给控制器的构造函数时,我的应用程序抛出System.InvalidOperationException
。 However, when I switch it out for the interface, it works. 但是,当我将其切换为接口时,它可以工作。 What is the reason for this? 这是什么原因呢?
In Startup.cs
在Startup.cs
services.AddScoped<IMailService, MailService>();
In my Controller
在我的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;
}
Many thanks! 非常感谢!
services.AddScoped<IMailService, MailService>();
Because of that line. 因为那条线。 You are telling the DI service to inject an instance of MailService
in the constructors when it encounters a parameter in the constructor of type IMailService
. 您要告诉DI服务在IMailService
类型的构造函数中遇到参数时,将其注入构造函数中的MailService
实例。
You have nothing defined for injecting (replacing) instances of type MailService
. 您没有为注入(替换) MailService
类型的实例定义任何内容。
What you have now is good practice, do not change it. 您现在拥有的是好的做法,请不要更改它。 You want to program against interfaces when possible. 您希望在可能的情况下针对接口进行编程。 This is also called interface based programming and there are many benefits. 这也称为基于接口的编程 ,有很多好处。
See also a possibly related question: What does it mean to "program to an interface"? 另请参见一个可能相关的问题: “对接口进行编程”是什么意思?
I noticed this too. 我也注意到了这一点。 Back when we used Unity for DI, it would be fine with resolving a concrete class you requested, even if you had not specifically added it to the container. 回到我们使用Unity for DI时,即使您没有专门将其添加到容器中,也可以通过解析您所请求的具体类来解决。
With .NET Core dependency injection, it requires that you specifically declare the services you are injecting. 使用.NET Core依赖项注入,它要求您专门声明要注入的服务。 Even though it could resolve your concrete class, I'm guessing the decision was made at some point in the development process to require this. 即使它可以解决您的具体课程,但我猜这个决定是在开发过程中的某个时候做出的,需要这样做。 So your code would work if you did: 因此,如果执行以下操作,您的代码将起作用:
services.AddScoped<MailService>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.