To break down the error message:
Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.
That is saying that your application is trying to create an instance of BlogController
but it doesn't know how to create an instance of BloggerRepository
to pass into the constructor.
Now look at your startup:
services.AddScoped<IBloggerRepository, BloggerRepository>();
That is saying whenever a IBloggerRepository
is required, create a BloggerRepository
and pass that in.
However, your controller class is asking for the concrete class BloggerRepository
and the dependency injection container doesn't know what to do when asked for that directly.
I'm guessing you just made a typo, but a fairly common one. So the simple fix is to change your controller to accept something that the DI container does know how to process, in this case, the interface:
public BlogController(IBloggerRepository repository)
// ^
// Add this!
{
_repository = repository;
}
Note that some objects have their own custom ways to be registered, this is more common when you use external Nuget packages, so it pays to read the documentation for them. For example if you got a message saying:
Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' ...
Then you would fix that using the custom extension method provided by that library which would be:
services.AddHttpContextAccessor();
For other packages - always read the docs.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…