简体   繁体   English

ASP.NET Core 错误:尝试激活时无法解析类型服务

[英]ASP.NET Core error: Unable to resolve service for type while attempting to activate

I get an error我收到一个错误

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。 InvalidOperationException: Unable to resolve service for type Employees.Models.EmployeesContext while attempting to activate Employees.Areas.Admin.Controllers.DepartmentsController . InvalidOperationException:在尝试激活Employees.Areas.Admin.Controllers.DepartmentsController时,无法解析Employees.Models.EmployeesContext类型的服务。

Here is my code:(Database first)这是我的代码:(数据库优先)

Model:( Departments.cs )型号:( 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; }
    }
}

Model( EmployeesContext.cs )模型( 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);
            });

Controller:( DepartmentsController )控制器:( 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>();
    }
}

Please help me.请帮我。

You need to Register and configure your context in Startup.cs您需要在Startup.cs注册和配置您的context

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

According to Docs根据文档

Registers the given context as a service in the Microsoft.Extensions.DependencyInjection.IServiceCollection.将给定的上下文注册为 Microsoft.Extensions.DependencyInjection.IServiceCollection 中的服务。 You use this method when using dependency injection in your application.在您的应用程序中使用依赖注入时,您可以使用此方法。

And delete your OnConfiguration method并删除您的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;");
            }
        }

If you use OnConfiguration in your DbContext then you can simply create your Context instance without passing the DbContextOptionsBuilder .如果您在DbContext使用OnConfiguration ,那么您可以简单地创建您的Context实例,而无需传递DbContextOptionsBuilder

For example:例如:

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

According to DOCS根据DOCS

An application can simply instantiate such a context without passing anything to its constructor应用程序可以简单地实例化这样的上下文,而无需向其构造函数传递任何内容

In Startup.ConfigureServices , you need register your context like this :Startup.ConfigureServices ,您需要像这样注册您的上下文:

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

More information :更多信息 :

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 核心依赖注入错误 - 尝试激活“服务”时无法解析“存储库”类型的服务 - ASP.NET Core Dependency Injection error - Unable to resolve service for type “Repository” while attempting to activate “Service” ASP.NET 核心错误:System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Core error: System.InvalidOperationException: Unable to resolve service for type while attempting to activate ASP.NET Core通用主机(HostBuilder)尝试激活时无法解析类型…的服务 - ASP.NET Core Generic Host (HostBuilder) Unable to resolve service for type … while attempting to activate ASP.NET Core InvalidOperationException:尝试激活UserStore时无法解析DbContext类型的服务 - ASP.NET Core InvalidOperationException: Unable to resolve service for type DbContext while attempting to activate UserStore ASP.NET 核心 - System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Core - System.InvalidOperationException: Unable to resolve service for type while attempting to activate ASP.Net Core - 尝试激活 *Controller 时无法解析 *Context 类型的服务 - ASP.Net Core - Unable to resolve service for type *Context while attempting to activate *Controller .net Core 6 - 尝试激活时无法解析服务类型 - .net Core 6 - Unable to resolve service for type while attempting to activate ASP.NET CORE:尝试激活“API.Controllers.UsersController”时无法解析“API.SQLConnection.IDBConnection”类型的服务 - ASP.NET CORE : Unable to resolve service for type 'API.SQLConnection.IDBConnection' while attempting to activate 'API.Controllers.UsersController' NET Core InvalidOperationException:尝试激活时无法解析类型服务 - NET Core InvalidOperationException: Unable to resolve service for type while attempting to activate ASP.NET Core Web API - 尝试激活“AuthService”时无法解析“Serilog.ILogger”类型的服务 - ASP.NET Core Web API - Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'AuthService'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM