2016-11-30 243 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>(); 
相關問題