c# - 在自己的 ServiceCollection 中获取 IConfiguration

标签 c# asp.net-core dependency-injection .net-core asp.net-core-2.2

我正在制作 fixture到我的tests .

在我的 FixtureFactory我自己做 ServiceCollection :

    private static ServiceCollection CreateServiceCollection()
    {
        var services = new ServiceCollection();

        services.AddScoped<IConfiguration>();
        services.AddScoped<ITokenService, TokenService>();
        services.AddDbContext<TaskManagerDbContext>(o => o.UseInMemoryDatabase(Guid.NewGuid().ToString()));
        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        {
            options.Password.RequiredLength = 6;
            options.Password.RequireLowercase = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireDigit = false;
            options.User.RequireUniqueEmail = true;
        }).AddEntityFrameworkStores<TaskManagerDbContext>();

        return services;
    }

然后,我得到这个 services来自 scope :

    var services = CreateServiceCollection().BuildServiceProvider().CreateScope();

    var context = services.ServiceProvider.GetRequiredService<TaskManagerDbContext>();
    var userManager = services.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    var roleManager = services.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var signInManager = services.ServiceProvider.GetRequiredService<SignInManager<ApplicationUser>>();
    var tokenService = services.ServiceProvider.GetRequiredService<TokenService>();

当我添加 TokenService 时问题开始了到我的ServiceCollection .

TokenService 的构造函数看起来像这样:

    private readonly IConfiguration configuration;

    private readonly UserManager<ApplicationUser> userManager;

    public TokenService(IConfiguration configuration, UserManager<ApplicationUser> userManager)
    {
        this.configuration = configuration;
        this.userManager = userManager;
    }

当我启动我的 Core 时效果很好应用程序,但无法从 ServiceCollection 运行我在上面提到过。

在测试中,我开始遇到这个错误:

Message: System.AggregateException : One or more errors occurred. (Cannot instantiate implementation type 'Microsoft.Extensions.Configuration.IConfiguration' for service type 'Microsoft.Extensions.Configuration.IConfiguration'.) (The following constructor parameters did not have matching fixture data: ServicesFixture fixture) ---- System.ArgumentException : Cannot instantiate implementation type 'Microsoft.Extensions.Configuration.IConfiguration' for service type 'Microsoft.Extensions.Configuration.IConfiguration'. ---- The following constructor parameters did not have matching fixture data: ServicesFixture fixture

当我添加 services.AddScoped<IConfiguration>(); 时,此错误开始显示到我的ServiceCollection当我开始获得所需的服务时 TokenService .

我的问题是,如何正确注册Configuration我在 Service 中使用?

我正在使用 Configurationsettings.json 获取项目.

编辑:

我的 fixture和样本测试类:

public class ServicesFixture
{
    public TaskManagerDbContext Context { get; private set; }

    public UserManager<ApplicationUser> UserManager { get; private set; }

    public RoleManager<IdentityRole> RoleManager { get; private set; }

    public SignInManager<ApplicationUser> SignInManager { get; private set; }

    public TokenService TokenService { get; private set; }

    public ServicesFixture()
    {
        var servicesModel = ServicesFactory.CreateProperServices();

        this.Context = servicesModel.Context;
        this.UserManager = servicesModel.UserManager;
        this.RoleManager = servicesModel.RoleManager;
        this.SignInManager = servicesModel.SignInManager;
        this.TokenService = servicesModel.TokenService;
    }

    [CollectionDefinition("ServicesTestCollection")]
    public class QueryCollection : ICollectionFixture<ServicesFixture>
    {
    }
}

测试:

[Collection("ServicesTestCollection")]
public class CreateProjectCommandTests
{
    private readonly TaskManagerDbContext context;

    public CreateProjectCommandTests(ServicesFixture fixture)
    {
        this.context = fixture.Context;
    }
}

EDIT2

当我删除 AddScoped<IConfiguration>(); 时从我的收集和运行测试中,我得到这个错误:

Message: System.AggregateException : One or more errors occurred. (No service for type 'TaskManager.Infrastructure.Implementations.TokenService' has been registered.) (The following constructor parameters did not have matching fixture data: ServicesFixture fixture) ---- System.InvalidOperationException : No service for type 'TaskManager.Infrastructure.Implementations.TokenService' has been registered. ---- The following constructor parameters did not have matching fixture data: ServicesFixture fixture

最佳答案

您添加了 IConfiguration 但没有实现。

startup.cs 中,框架会在幕后创建一个实现并将其添加。您将必须使用 ConfigurationBuilder

执行相同的操作
var builder = new ConfigurationBuilder()
    //.SetBasePath("path here") //<--You would need to set the path
    .AddJsonFile("appsettings.json"); //or what ever file you have the settings

IConfiguration configuration = builder.Build();

services.AddScoped<IConfiguration>(_ => configuration);

//...

关于c# - 在自己的 ServiceCollection 中获取 IConfiguration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57115707/

相关文章:

c# - 在 C# WinForms 中预览文档(Word、Excel、PDF、文本文件等)?

c# - ASP.NET 生产服务器 PDB 文件

c# - Group by 会生成巨大的查询

angular - ASP.NET核心: Windows Authentication with OPTIONS exception (CORS preflight)

php - Symfony 3.3 依赖注入(inject)变化

c# - NpgSQL 抛出异常

c# - 如何配置多对一关系?

sql-server - 在 ASP.Net/Entity Framework Core 中为远程 SQL 连接字符串指定登录凭据

c# - Windows开发如何快速学习Autofac?

JavaFX 应用程序中的 Spring 应用程序上下文