您好,我收到此错误:
无效操作异常: 无法解析类型的服务 "RegistrationMVC.Model.OurDbContext",同时尝试激活 "注册MVC.Controllers.HomeController"。
我不知道是什么原因造成的,可能是有依赖关系的东西吗?
启动.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?}");
});
}
}
首页控制器
OurDbContext
一些容器会自动实例化像 OurDbContext 这样的类(只要它可以成功构造(,因为它是一个可以构造的类型,而另一些容器如果未在依赖项容器中定义 OurDbContext,则会引发异常。 所以它可以像没有注册我们的数据库上下文一样简单,并且容器以这种方式运行......