无法解析 ApplicationDbContext 中类型的服务

Unable to resolve service for type in ApplicationDbContext

当我尝试使用 dnx ef migrations add Mig 添加迁移时,我在控制台中出现以下异常:

Unable to resolve service for type 'Microsoft.AspNet.Http.IHttpContextAcccessor' while attempting to activate 'NewLibrary.Models.ApplicationDbContext'.

我的ApplicationDbContext:

public class ApplicationDbContext : DbContext
{
    private readonly IHttpContextAccessor _accessor;

    public ApplicationDbContext(IHttpContextAccessor accessor)
    {
        _accessor = accessor;
    }
}

有什么问题吗?

我应该如何正确地将依赖项添加到 ApplicationDbContext 构造函数?

DI 不会通过命令行设置,这就是您遇到上述异常的原因。

您在评论中解释说您希望通过 IHttpContextAccessor 访问 HttpContext,这通常在 运行 时间可用。

迁移未在 运行 时间应用,此时 DI 已配置并可用。

您可能需要阅读 Configuring a DbContext。本文档适用于 EF7 以上版本

我发现这个论坛让我找到了以下解决方案:https://github.com/aspnet/EntityFrameworkCore/issues/4232

创建新服务class和接口:

    using Microsoft.AspNetCore.Http;
    using MyProject.Interfaces;
    using System.Collections.Generic;
    using System.Linq;

    namespace MyProject.Web.Services
    {
        public interface IUserResolverService
        {
            string GetCurrentUser();
        }

        public class UserResolverService : IUserResolverService
        {
            private readonly IHttpContextAccessor _context;
            public UserResolverService(IEnumerable<IHttpContextAccessor> context)
            {
                _context = context.FirstOrDefault();
            }

            public string GetCurrentUser()
            {
                return _context?.HttpContext?.User?.Identity?.Name ?? "unknown_user";
            }
        }
    }

并将其注册到您的 DI 容器(例如Startup.cs)

    services.AddTransient<IUserResolverService, UserResolverService>();

然后在您的 DbContext 中,使用 userResolverService 代替 IHTTPContextAccessor 获取用户名

    private readonly IUserResolverService userResolverService;
    public ApplicationDbContext(IUserResolverService userResolverService) : base()
    {
        this.userResolverService = userResolverService;

        var username = userResolverService.GetCurrentUser();
...