Home > Backend Development > C++ > Why Does My .NET Core MVC Application Fail to Inject a Repository Dependency?

Why Does My .NET Core MVC Application Fail to Inject a Repository Dependency?

Susan Sarandon
Release: 2025-01-23 18:09:12
Original
719 people have browsed it

.NET Core MVC app dependency injection error: Unable to resolve dependencies for interface

Problem Description

A .NET Core MVC app encountered an error while trying to inject a repository dependency into a controller. The error message is as follows:

<code>InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.</code>
Copy after login

Analysis

This error indicates that the application cannot create an instance of the BloggerRepository class to pass to the BlogController constructor. Although BloggerRepository is registered in the startup class:

<code class="language-csharp">services.AddScoped<IBloggerRepository, BloggerRepository>();</code>
Copy after login

Solution

The problem is that the controller class directly requests the concrete BloggerRepository class. However, the dependency injection container only knows how to create instances of the IBloggerRepository interface. To resolve this error, the controller should be adjusted to accept the interface:

<code class="language-csharp">public BlogController(IBloggerRepository repository)
{
    _repository = repository;
}</code>
Copy after login

Other instructions

For external NuGet packages, be sure to check their documentation as they may have specific registration requirements. For example, to resolve an error message about IHttpContextAccessor:

<code>Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' ...</code>
Copy after login

The solution is to use a custom extension method:

<code class="language-csharp">services.AddHttpContextAccessor();</code>
Copy after login

Why Does My .NET Core MVC Application Fail to Inject a Repository Dependency?

The above is the detailed content of Why Does My .NET Core MVC Application Fail to Inject a Repository Dependency?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template