. NET Базовый контекст с несколькими данными - PullRequest
0 голосов
/ 31 марта 2020

Я разрабатываю среду, в которой мне нужно отделить библиотеки аутентификации от библиотек приложений. Для этого я создал базовое приложение webapi. net и библиотеку, в которой будут храниться классы аутентификации.

DataContext для моей библиотеки Auth:

пространство имен Auth.LIB.Data {publi c класс AuthDataContext: IdentityDbContext, UserRole, IdentityUserLogin, IdentityRoleClaim, IdentityUserToken> {100 *

}

В моем Core Web API у меня есть другой контекст данных, который выглядит следующим образом:

using Microsoft.EntityFrameworkCore; использование Core.API.Models.Core;

пространство имен Core.API.Data {publi c class DataContext: DbContext {publi c DataContext (опции DbContextOptions): база (опции) {}

    public DbSet<model1> Model1s{ get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    { }
}

}

Мой файл Startup.cs выглядит следующим образом:

пространство имен Core.API {publi c запуск класса {publi c Запуск (конфигурация IConfiguration) {Настройка = конфигурация; }

    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.AddControllers();


        // Set up MVC for defaulting to required authorization
        services.AddMvc(options =>
        {
            /// This will force every user to authenticate every method within our MVC endpoint
            var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


        // Define the authorization policies
        services.AddAuthorization(options =>
        {
            options.AddPolicy("AdminRolePolicy", policy => policy.RequireRole("Admin"));
            options.AddPolicy("ServiceRoelPolicy", policy => policy.RequireRole("Service"));
            //options.AddPolicy("CustomerRolePolicy", policy => policy.RequireRole("Admin", "Customer"));
            //options.AddPolicy("ProjectRolePolicy", policy => policy.RequireRole("Admin", "Project Manager", "Contractor", "Vendor"));
        });

        // We need CORS for authentication, revisit this
        services.AddCors();

        // Inject services            
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<ICoreRepsository, CoreRepository>();
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }


    public void ConfigureDevelopmentServices(IServiceCollection services)
    {
        //services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnectionSQLLite")));
        services.AddDbContext<AuthDataContext>(x => x.UseMySql(Configuration.GetConnectionString("AuthConnectionString")));
        services.AddDbContext<DataContext>(x => x.UseMySql(Configuration.GetConnectionString("CoreConnectionString")));
        ConfigureServices(services);
    }

    // This will get called in production modes
    public void ConfigureProductionServices(IServiceCollection services)
    {
        services.AddDbContext<AuthDataContext>(x => x.UseMySql(Configuration.GetConnectionString("AuthConnectionString")));
        services.AddDbContext<DataContext>(x => x.UseMySql(Configuration.GetConnectionString("CoreConnectionString")));
        ConfigureServices(services);
    }

}

}

Все компилируются без проблем. Однако при запуске приложения появляется следующая ошибка:

Необработанное исключение. System.AggregateException: некоторые службы не могут быть созданы (Ошибка при проверке дескриптора службы 'ServiceType: Auth.LIB.Data.IUserRepository Lifetime: Scoped PracticeType: Auth.LIB.Data.UserRepository': невозможно разрешить службу для типа ' Microsoft.AspNetCore.Identity.UserManager 1[Auth.LIB.Models.User]' while attempting to activate 'Auth.LIB.Data.UserRepository'.) ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Auth.LIB.Data.IUserRepository Lifetime: Scoped ImplementationType: Auth.LIB.Data.UserRepository': Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager 1 [Auth.LIB.Models.User] 'при попытке активировать' Auth.LIB.Data.UserRepository '. ---> System.InvalidOperationException: невозможно разрешить службу для типа' Microsoft.AspNetCore. ) в Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider () в Microsoft.Extensions.Hosting.HostBuilder.Build () в Core.API.Program.Main (String [] args) в

Любые мысли о том, почему это происходит? Спасибо

...