2017-05-26 61 views
-2

你好,我得到這個錯誤:出現InvalidOperationException錯誤

InvalidOperationException: Unable to resolve service for type 'RegistrationMVC.Model.OurDbContext' while attempting to activate 'RegistrationMVC.Controllers.HomeController'.

我不知道什麼可能導致它,可能是一些與依賴關係?

startup.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNetCore.Builder; 
using Microsoft.AspNetCore.Hosting; 
using Microsoft.Extensions.Configuration; 
using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Logging; 
using WebApplicationCore.NetCore.DataAccess; 
using WebApplicationCore.NetCore.BusinessLogic; 
namespace WebApplicationCore.NetCore 
    public class Startup 
    { 
     public Startup(IHostingEnvironment env) 
     { 
      var builder = new ConfigurationBuilder() 
       .SetBasePath(env.ContentRootPath) 
       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
       .AddEnvironmentVariables(); 
      Configuration = builder.Build(); 
     } 

    public IConfigurationRoot Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddMvc(); 

     services.AddSingleton<IConfigurationRoot>(sp => { return this.Configuration; }); 
     services.AddScoped<IContactDataAccess, ContactDataAccess>(); 
     services.AddScoped<IContactBusinessLogic, ContactBusinessLogic>(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
      app.UseBrowserLink(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 

     app.UseStaticFiles(); 

     app.UseMvc(routes => 
     { 
      routes.MapRoute(
       name: "default", 
       template: "{controller=Home}/{action=Index}/{id?}"); 
     }); 
    } 
} 

HomeController

OurDbContext

+1

您不會在HomeController的構造函數要求的任何位置註冊「OurDbContext」。你還應該閱讀[問]並確保你的問題中的代碼是[mcve]。 – CodeCaster

回答

0

一些容器將自動實例化等OurDbContext類(只要它可以被成功構建)自動因爲它是一個類型,可以如果OurDbContext未在依賴容器中定義,則其他人會拋出異常。所以它可以像OurDbContext沒有註冊一樣簡單,並且容器按照這種方式工作...

相關問題