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>
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>
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>
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>
The solution is to use a custom extension method:
<code class="language-csharp">services.AddHttpContextAccessor();</code>
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!