InvalidOperationException:无法解析类型为'Microsoft.EntityFrameworkCore.DbContextOptions`1的服务

时间:2018-10-22 06:40:07

标签: asp.net asp.net-core asp.net-core-2.0 asp.net-core-webapi asp.net-core-2.1

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

  

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

,然后输入URL https://localhost:44366/api/login/Authenticate 告诉我这个错误

  

找不到该本地主机页面未找到以下网址的网页:https://localhost:44366/api/login/Authenticate   HTTP错误404

出什么问题了?我该如何解决这个问题?

我的代码=>

LoginController:

 [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();
    }

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;
    }

1 个答案:

答案 0 :(得分:2)

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

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

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

然后在ConfigureServices中注册它:

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

和其中定义了ConnectionString的appSettings.json:

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