Troubleshoot dependency injection errors: Solve the service resolution problem when the controller is activated
Dependency Injection (DI) is an integral part of modern software development. However, errors can occur during the DI process, especially if the service cannot be successfully resolved for controller activation.
Error message
<code>InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.</code>
This error indicates that the DI container was unable to create an instance of BloggerRepository for injection into the BlogController constructor during controller activation.
Problem Analysis
To understand the root cause, let us examine the provided code snippet:
Warehouse interface and implementation
<code>public interface IBloggerRepository { ... } public class BloggerRepository : IBloggerRepository { ... }</code>
Controller
<code>public class BlogController : Controller { private readonly IBloggerRepository _repository; public BlogController(BloggerRepository repository) // ^ // 问题在此:构造函数请求具体的类 { _repository = repository; } public IActionResult Index() { ... } }</code>
Startup configuration
<code>public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddScoped<IBloggerRepository, BloggerRepository>(); }</code>
Solution
The problem is that the BlogController constructor requests the concrete class BloggerRepository. However, the DI container has registered an instance of the interface IBloggerRepository. To fix this, the controller should be updated to accept interfaces instead of concrete classes:
<code>public BlogController(IBloggerRepository repository) // ^ // 修复:构造函数接受接口 { _repository = repository; }</code>
After making this change, the DI container can successfully resolve the service and inject an instance of BloggerRepository into the BlogController.
Other notes
In rare cases, certain objects may require specific registration techniques. For example, if you encounter the following error:
<code>Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' ...</code>
Such dependencies can be resolved using custom extension methods provided by external libraries. Always consult the external library's documentation for specific registration instructions.
The above is the detailed content of Why is my ASP.NET Core controller failing to activate due to a dependency injection error?. For more information, please follow other related articles on the PHP Chinese website!