Solution to controller dependency injection failure in .NET Core MVC application
In your .NET Core MVC application, an error occurs when trying to inject BloggerRepository
into BlogController
with the following message:
<code>InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.</code>
Let’s analyze the code to understand this error:
Warehouse level:
<code>public interface IBloggerRepository { ... } public class BloggerRepository : IBloggerRepository { ... }</code>
Controller:
<code>public class BlogController : Controller { private readonly IBloggerRepository _repository; public BlogController(BloggerRepository repository) { ... } }</code>
Startup.cs:
<code>services.AddScoped<IBloggerRepository, BloggerRepository>();</code>
error indicates that the dependency injection system cannot provide a BlogController
instance for the BloggerRepository
constructor.
The problem is that the controller expects a concrete class for BloggerRepository
, while the dependency injection container is told to register the interface IBloggerRepository
with the concrete implementation.
Solution:
To solve this problem, modify the controller's constructor so that it accepts an interface instead of a concrete class:
<code>public BlogController(IBloggerRepository repository) { ... }</code>
With this modification, the dependency injection container can now successfully resolve dependencies and provide an instance of IBloggerRepository
which will automatically be instantiated as BloggerRepository
.
Note: Different packages may have their own way of registering services. It is recommended to always consult its documentation for specific guidance.
The above is the detailed content of Why Does My .NET Core MVC App Fail to Inject a Registered Service into a Controller?. For more information, please follow other related articles on the PHP Chinese website!