Home >Backend Development >C++ >Why Does My .NET Core MVC App Fail to Inject a Registered Service into a Controller?

Why Does My .NET Core MVC App Fail to Inject a Registered Service into a Controller?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 17:47:09267browse

Why Does My .NET Core MVC App Fail to Inject a Registered Service into a Controller?

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>
The

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn