2016-11-30 217 views
15

我创建了.NET Core MVC应用程序,并使用依赖注入和存储库模式将存储库注入到控制器。不过,我得到一个错误:ASP.NET核心依赖注入错误:尝试激活时无法解析类型服务

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); 
     } 
    } 
} 

我不知道我在做什么错。有任何想法吗?

回答

39

该异常说明它无法解析WebApplication1.Data.BloggerRepository的服务,因为控制器上的构造函数正在请求具体类而不是接口。因此,只要改变:

public BlogController(IBloggerRepository repository) 
//     ^
//     Add this! 
{ 
    _repository = repository; 
} 
+3

我觉得缺少:( – kimbaudi

+6

发生在我们身上的所有这么笨我只花了30分钟试图弄清楚什么是错我的代码和在这里结束了 - “”当然这不是吗?“*我想到了自己......当然是!谢谢! –

+1

不能认真......难以让错误信息更有用.. – goamn

3

只有当人有像我这样的,我做的EntityFramework的教程与现有数据库相同的情况,但在模型文件夹中创建新的数据库上下文时,我们需要更新在启动的背景下,而不仅是在services.AddDbContext但AddIdentity太多,如果你有一个用户认证

services.AddDbContext<NewDBContext>(options => 
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

services.AddIdentity<ApplicationUser, IdentityRole>() 
       .AddEntityFrameworkStores<NewDBContext>() 
       .AddDefaultTokenProviders(); 
3

在我来说,我试图做的依赖注入这需要构造函数参数的对象。在这种情况下,启动时我刚提供的参数从配置文件,例如:

var config = Configuration.GetSection("subservice").Get<SubServiceConfig>(); 
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2)); 
1

如果您正在使用AutoFac并收到此错误,你应该增加一个“作为”语句来指定服务的具体的实现实现。

即,你应该写:

containerBuilder.RegisterType<DataService>().As<DataService>(); 

,而不是

containerBuilder.RegisterType<DataService>();