【问题标题】:ASP.NET Core error: Unable to resolve service for type while attempting to activateASP.NET Core 错误:尝试激活时无法解析服务类型
【发布时间】:2023-03-24 11:31:01
【问题描述】:

我收到一个错误

处理请求时发生未处理的异常。 InvalidOperationException:尝试激活 Employees.Areas.Admin.Controllers.DepartmentsController 时无法解析类型 Employees.Models.EmployeesContext 的服务。

这是我的代码:(数据库优先)

型号:(Departments.cs)

using System;
using System.Collections.Generic;

namespace Employees.Models
{
    public partial class Departments
    {
        public Departments()
        {
            EmployeeDepartments = new HashSet<EmployeeDepartments>();
        }

        public string DepartmentCode { get; set; }
        public string Name { get; set; }
        public DateTime? CreatedOn { get; set; }

        public ICollection<EmployeeDepartments> EmployeeDepartments { get; set; }
    }
}

型号(EmployeesContext.cs)

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace Employees.Models
{
    public partial class EmployeesContext : DbContext
    {
        public EmployeesContext()
        {
        }

        public EmployeesContext(DbContextOptions<EmployeesContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Departments> Departments { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
modelBuilder.Entity<Departments>(entity =>
            {
                entity.HasKey(e => e.DepartmentCode);

                entity.Property(e => e.DepartmentCode)
                    .HasMaxLength(10)
                    .IsUnicode(false)
                    .ValueGeneratedNever();

                entity.Property(e => e.CreatedOn).HasColumnType("datetime");

                entity.Property(e => e.Name).HasMaxLength(100);
            });

控制器:(DepartmentsController)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Employees.Models;

namespace Employees.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class DepartmentsController : Controller
    {
        private readonly EmployeesContext _context;

        public DepartmentsController(EmployeesContext context)
        {
            _context = context;
        }

        // GET: Admin/Departments
        public async Task<IActionResult> Index()
        {
            return View(await _context.Departments.ToListAsync());
        }

        // GET: Admin/Departments/Details/5
        public async Task<IActionResult> Details(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var departments = await _context.Departments
                .FirstOrDefaultAsync(m => m.DepartmentCode == id);
            if (departments == null)
            {
                return NotFound();
            }

            return View(departments);
        }

        // GET: Admin/Departments/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Admin/Departments/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("DepartmentCode,Name,CreatedOn")] Departments departments)
        {
            if (ModelState.IsValid)
            {
                _context.Add(departments);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(departments);
        }

        // GET: Admin/Departments/Edit/5
        public async Task<IActionResult> Edit(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var departments = await _context.Departments.FindAsync(id);
            if (departments == null)
            {
                return NotFound();
            }
            return View(departments);
        }

        // POST: Admin/Departments/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(string id, [Bind("DepartmentCode,Name,CreatedOn")] Departments departments)
        {
            if (id != departments.DepartmentCode)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(departments);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DepartmentsExists(departments.DepartmentCode))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(departments);
        }

        // GET: Admin/Departments/Delete/5
        public async Task<IActionResult> Delete(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var departments = await _context.Departments
                .FirstOrDefaultAsync(m => m.DepartmentCode == id);
            if (departments == null)
            {
                return NotFound();
            }

            return View(departments);
        }

        // POST: Admin/Departments/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(string id)
        {
            var departments = await _context.Departments.FindAsync(id);
            _context.Departments.Remove(departments);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool DepartmentsExists(string id)
        {
            return _context.Departments.Any(e => e.DepartmentCode == id);
        }
    }
}

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Employees.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Employees
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

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

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            {
                var connectionString = @"DefaultConnection";
                services.AddDbContext<EmployeesContext>(options => options.UseSqlServer(connectionString));
            }
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

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

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=PHONG-PC\\SQLEXPRESS;Database=Employees;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Employees
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

请帮帮我。

【问题讨论】:

  • 您需要在Startup.ConfigureServices 方法中注册您的服务。可以显示Startup.ConfigureServices吗?
  • 我刚刚编辑了 Startup.cs。
  • 什么是 ApplicationDbContext?
  • 它是空的,我不使用它

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

您需要在Startup.cs中注册并配置您的context

 public void ConfigureServices(IServiceCollection services)
            {
                var connectionString = @"Server=.\\SQLExpress;Database=Employees;Trusted_Connection=True;";
                services.AddDbContext<EmployeesContext>(options => options.UseSqlServer(connectionString));
            }

根据Docs

将给定的上下文注册为服务 Microsoft.Extensions.DependencyInjection.IServiceCollection。你用 在您的应用程序中使用依赖注入时使用此方法。

并删除您的OnConfiguration 方法

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("Server=.\\SQLExpress;Database=Employees;Trusted_Connection=True;");
            }
        }

如果您在DbContext 中使用OnConfiguration,那么您可以简单地创建您的Context 实例,而无需传递DbContextOptionsBuilder

例如:

using (var context = new EmployeeContext())
{
  // do stuff
}

根据DOCS

应用程序可以简单地实例化这样的上下文而无需传递 对其构造函数的任何内容

【讨论】:

  • 我又得到一个错误:( InvalidOperationException: Instance failure. 请帮忙。
  • 而不是"DefaultConnection" in Startup.cs 传递您的实际连接字符串。
  • 可能是您的连接字符串在 appsettings.json 中有不同的键。
  • 你可以简单地将实体框架配置替换成这个var connectionString = @"Server=.\\SQLExpress;Database=Employees;Trusted_Connection=True;"; services.AddDbContext&lt;EmployeesContext&gt;(options =&gt; options.UseSqlServer(connectionString));
  • 好的,步骤如下: 1) 从EmployeesContext 类中删除默认构造函数和 OnConfiguration 方法。 2)如上述评论中所述,使用您的有效连接字符串注册您的实体框架。请在此之后更新您的EmployeeContextStartup.cs
【解决方案2】:

Startup.ConfigureServices,你需要像这样注册你的上下文:

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

更多信息:

https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext

https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontext

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 2017-04-15
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多