如果我们现在运行应用程序,我们将可能遇到一个异常:
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);
}