首页 > 解决方案 > InvalidOperationException:无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions`1 的服务”

问题描述

我需要使用 web api 创建登录,但是当我输入此 url 时https://localhost:44366/api/login显示此错误:

InvalidOperationException:尝试激活“IRI.DataLayer.Context.ApplicationDbContext”时,无法解析“Microsoft.EntityFrameworkCore.DbContextOptions`1[IRI.DataLayer.Context.ApplicationDbContext]”类型的服务。

然后输入 URLhttps://localhost:44366/api/login/Authenticate 显示这个错误

找不到此 localhost 页面没有找到该网址的网页:https://localhost:44366/api/login/Authenticate HTTP ERROR 404

有什么问题 ?我怎么解决这个问题?

我的代码 =>

登录控制器:

 [Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    private readonly IApplicationUserManager _userManager;
    private readonly IApplicationSignInManager _signIn;
    private readonly IOptionsSnapshot<SiteSetting> _options;
    private readonly ILogger<LoginController> _logger;
    public LoginController(IApplicationUserManager userManager
        , IApplicationSignInManager signIn
        , IOptionsSnapshot<SiteSetting> options
        , ILogger<LoginController> logger)
    {
        _userManager = userManager;
        _userManager.CheckArgumentIsNull(nameof(_userManager));
        _options = options;
        _options.CheckArgumentIsNull(nameof(_options));
        _signIn = signIn;
        _signIn.CheckArgumentIsNull(nameof(_signIn));
        _logger = logger;
        _logger.CheckArgumentIsNull(nameof(_logger));

    }

    public async Task<IActionResult> Authenticate(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByNameAsync(model.username);
            if (user == null)
            {
                return BadRequest(Messages.IncorrectUsernamePassword);
            }
            if (!user.IsActive)
            {
                return BadRequest(Messages.NotActive);
            }
            if (_options.Value.EnableEmailConfirmation
                && await _userManager.IsEmailConfirmedAsync(user))
            {
                return BadRequest(Messages.EmailConfirmation);
            }
        }
        var result = await _signIn.PasswordSignInAsync(
                                model.username,
                                model.password,
                                model.rememberme,
                                lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation(1, $"{model.username} logged in");
            return Ok(User);
        }
        if (result.RequiresTwoFactor)
        {
            //TODO Create Function for TowFactor 
        }
        if (result.IsNotAllowed)
        {
            return BadRequest(Messages.NotAllowed);
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning(2, $"{model.username} قفل شده‌است.");
            return BadRequest(Messages.IsLocked);
        }
        return BadRequest(Messages.IncorrectUsernamePassword);
    }
}

}

启动 :

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddCustomServices();
    }

添加自定义服务:

 public static IServiceCollection AddCustomServices(this IServiceCollection services)
    {
        services.AddScoped<IUnitOfWork, ApplicationDbContext>();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped<IPrincipal>(provider =>
            provider.GetService<IHttpContextAccessor>()?.HttpContext?.User ?? ClaimsPrincipal.Current);

        services.AddScoped<IApplicationSignInManager, ApplicationSignInManager>();
        services.AddScoped<SignInManager<User>, ApplicationSignInManager>();

        services.AddScoped<IApplicationUserManager, ApplicationUserManager>();
        services.AddScoped<UserManager<User>, ApplicationUserManager>();

        services.AddScoped<IApplicationUserStore, ApplicationUserStore>();
        services.AddScoped<UserStore<User, Role, ApplicationDbContext, int, UserClaim, UserRole, UserLogin, UserToken, RoleClaim>, ApplicationUserStore>();

        return services;
    }

标签: asp.netasp.net-coreasp.net-core-2.0asp.net-core-webapiasp.net-core-2.1

解决方案


您尚未在应用程序中配置 DbContext。

将 IdentityDbContext 添加到您的应用程序:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions options)
        : base(options)
    {
    }
}

然后在 ConfigureServices 中注册:

services.AddDbContextPool<ApplicationDbContext>(opt => opt.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

以及定义 ConnectionStrings 的 appSettings.json :

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=Server-Name; Database=DBName; Trusted_Connection=True; MultipleActiveResultSets=True;"
  }
}

推荐阅读