在自己的ServiceCollection中获取IConfiguration

时间:2019-07-19 15:40:35

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

我正在fixturetests

在我的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中使用。

在测试中,我开始出现此错误:

  

消息:System.AggregateException:发生一个或多个错误。 (无法实例化服务类型“ Microsoft.Extensions.Configuration.IConfiguration”的实现类型“ Microsoft.Extensions.Configuration.IConfiguration”。)(以下构造函数参数没有匹配的灯具数据:ServicesFixture灯具)   ---- System.ArgumentException:无法实例化服务类型“ Microsoft.Extensions.Configuration.IConfiguration”的实现类型“ Microsoft.Extensions.Configuration.IConfiguration”。   ----以下构造函数参数没有匹配的夹具数据:ServicesFixture夹具

当我将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>();并运行测试时,出现此错误:

  

消息:System.AggregateException:发生一个或多个错误。 (没有注册类型'TaskManager.Infrastructure.Implementations.TokenService'的服务。)(以下构造函数参数没有匹配的灯具数据:ServicesFixture灯具)   ---- System.InvalidOperationException:没有注册类型为'TaskManager.Infrastructure.Implementations.TokenService'的服务。   ----以下构造函数参数没有匹配的夹具数据:ServicesFixture夹具

1 个答案:

答案 0 :(得分:2)

您添加了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);

//...