如果我们现在运行应用程序,我们将可能遇到一个异常:
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'ControllerDI.Interfaces.IDateTime' while attempting to activate 'ControllerDI.Controllers.HomeController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
这个错误发生时,我们没有在我们的 Startup 类的 ConfigureServices 方法中配置服务。添加下面的服务到你的 ConfigureServices 方法中:
public void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddScoped<MessageService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
本文介绍了一个关于.NET Core应用程序中依赖注入出现异常的问题,并提供了解决方案。异常出现在尝试激活控制器时,原因是未能为类型IDateTime解析服务。通过在Startup.cs文件的ConfigureServices方法中正确注册所需的依赖项,可以解决此问题。

331

被折叠的 条评论
为什么被折叠?



