Нет службы для типа 'Microsoft.AspNetCore.Identity.UserManager при запуске приложения - PullRequest
0 голосов
/ 29 сентября 2018

У меня есть ApplicationDbContext, который находится в ClassLibrary с именем App.ClassLibrary.Здесь я выполняю миграцию БД и создание моделей.

У меня также есть другое приложение под названием App.UI, которое зависит от App.ClassLibrary.Однако, кажется, что когда я запускаю свое приложение, мой LoginPartial выдает мне эту ошибку

InvalidOperationException: нет службы для типа 'Microsoft.AspNetCore.Identity.UserManager`1 [Microsoft.AspNetCore.Identity.IdentityUser] 'был зарегистрирован.

Это мой запуск в моем App.UI

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString(DatabaseGlobals.ConnectionStringName)));
    services.AddMvc();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString(DatabaseGlobals.ConnectionStringName)));
    services.AddIdentity<Users,Roles>()
      .AddEntityFrameworkStores<ApplicationDbContext>()
      .AddDefaultTokenProviders();
}

// 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: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        serviceScope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();

    }
}

Это мой класс пользователей и ролей

public class Users : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime DateOfBirth { get; set; }
    private DateTime createdOn = DateTime.Now;
    public DateTime CreatedOn
    {
        get
        {
            return (createdOn == DateTime.MinValue) ? DateTime.Now : createdOn;
        }
        set
        {
            createdOn = value;
        }
    }
    private DateTime updatedOn = DateTime.Now;
    public DateTime UpdatedOn
    {
        get
        {
            return (updatedOn == DateTime.MinValue) ? DateTime.Now : updatedOn;
        }
        set
        {
            updatedOn = value;
        }
    }
}

public class Roles : IdentityRole
{
    [Required]
    public string ApplicationId { get; set; }
    public virtual Applications Application { get; set; }
}

И, наконец, это страница LoginPartial, которая дает мне ошибку:

@using Microsoft.AspNetCore.Identity

@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Logout</button>
            </li>
        </ul>
    </form>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li><a asp-area="Identity" asp-page="/Account/Register">Register</a></li>
        <li><a asp-area="Identity" asp-page="/Account/Login">Login</a></li>
    </ul>
}

Я попытался переключить SignInManager с <IdentityUser> на <Users>, но он не скомпилируется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...