问题描述
我创建了一个 .NET Core MVC 应用程序并使用依赖注入和存储库模式将存储库注入我的控制器.但是,我收到一个错误:
I created an .NET Core MVC application and use Dependency Injection and Repository Pattern to inject a repository to my controller. However, I am getting an error:
InvalidOperationException:尝试激活WebApplication1.Controllers.BlogController"时无法解析WebApplication1.Data.BloggerRepository"类型的服务.
InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.
模型(Blog.cs)
namespace WebApplication1.Models
{
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
}
DbContext (BloggingContext.cs)
using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;
namespace WebApplication1.Data
{
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
}
存储库(IBloggerRepository.cs 和 BloggerRepository.cs)
using System;
using System.Collections.Generic;
using WebApplication1.Models;
namespace WebApplication1.Data
{
internal interface IBloggerRepository : IDisposable
{
IEnumerable<Blog> GetBlogs();
void InsertBlog(Blog blog);
void Save();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;
namespace WebApplication1.Data
{
public class BloggerRepository : IBloggerRepository
{
private readonly BloggingContext _context;
public BloggerRepository(BloggingContext context)
{
_context = context;
}
public IEnumerable<Blog> GetBlogs()
{
return _context.Blogs.ToList();
}
public void InsertBlog(Blog blog)
{
_context.Blogs.Add(blog);
}
public void Save()
{
_context.SaveChanges();
}
private bool _disposed;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_context.Dispose();
}
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
Startup.cs(相关代码)
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IBloggerRepository, BloggerRepository>();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
控制器 (BlogController.cs)
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Data;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class BlogController : Controller
{
private readonly IBloggerRepository _repository;
public BlogController(BloggerRepository repository)
{
_repository = repository;
}
public IActionResult Index()
{
return View(_repository.GetBlogs().ToList());
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Blog blog)
{
if (ModelState.IsValid)
{
_repository.InsertBlog(blog);
_repository.Save();
return RedirectToAction("Index");
}
return View(blog);
}
}
}
我不确定我做错了什么.有什么想法吗?
I'm not sure what I'm doing wrong. Any ideas?
推荐答案
分解错误信息:
在尝试激活WebApplication1.Controllers.BlogController"时无法解析WebApplication1.Data.BloggerRepository"类型的服务.
Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.
也就是说,您的应用程序正在尝试创建 BlogController 的实例,但它不知道 如何 创建 BloggerRepository 传递给构造函数.
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>();
也就是说,每当需要 IBloggerRepository 时,创建一个 BloggerRepository 并将其传入.
That is saying whenever a IBloggerRepository is required, create a BloggerRepository and pass that in.
但是,您的控制器类正在请求具体类 BloggerRepository,而依赖注入容器在直接请求时不知道该怎么做.
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.
我猜你只是打错字了,但很常见.因此,简单的解决方法是更改您的控制器以接受 DI 容器确实知道如何处理的东西,在这种情况下,接口:
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;
}
请注意,有些对象有自己的自定义注册方式,这在您使用外部 Nuget 包时更为常见,因此阅读它们的文档是值得的.例如,如果您收到一条消息:
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:
无法解析类型Microsoft.AspNetCore.Http.IHttpContextAccessor"的服务...
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.
这篇关于ASP.NET Core 依赖注入错误:尝试激活时无法解析服务类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)