在嵌套类使用的配置设置

问题描述 投票:3回答:2

当我有嵌套,孩子们需要一些配置设置(即写在appsettings.json设置),做我需要做一个水桶接力传递配置儿童班班?

我不认为下面的例子是一个聪明的办法。有没有更好的做法?

Startup.cs

public Startup(IConfiguration configuration, ...)
    {
        ...
        this.Configuration = configuration;
        ...
    }

Parent.cs

public class Parent
{
    public Parent(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    private IConfiguration _configuration;
    private ChildOne _childOne;
    private ChildTwo _childTwo;

    public void InitializeChildren()
    {
        _childOne = new ChildOne(_configuration);
        _childTwo = new ChildTwo(_configuration);
    }
}

ChildOne.cs

public class ChildOne{
    public ChildOne(IConfiguration configuration){
        _propOne = configuration.GetSection("brahbrah").Value;
    }

    private string _propOne;
}
c# dependency-injection appsettings
2个回答
1
投票

域对象/模型只不过是数据的容器多。这些数据容器可以有需要的数据,而是因为他们是在您的应用程序的核心不应该依赖于依赖注入(直接)此数据。模型中的变化(或它的依赖),将最有可能导致更大的变化。

正如你在你的例子表明您想使用new操作实例化你的模型,并通过为IConfiguration作为参数。通过在您的数据容器需要IConfiguration你造成这样一种情况,如果返回的结果是否存在以及存在于它的每一个属性,并在数据容器之后设置适当值的模型将需要大量的检查。

较好地解决了这个问题,是通过注册一个专用的配置类,我们将其称为BrahBrahConfig来匹配你的榜样,在依赖注入框架。

public static IServiceCollection SetupDependencyInjection(this 
    IServiceCollection services, IConfiguration config)
{
    services.Configure<BrahBrahConfig>(config.GetSection("brahbrah"));

    return services;
}

在上面的例子中看到使用用于IServiceCollection Configure<TOptions>(this IServiceCollection services, IConfiguration config)过载可在NuGet包“Microsoft.Extensions.Options.ConfigurationExtensions”中找到的。

此重载使您能够直接注入IOptions的实例为您所选择的构造。

private BrahBrahConfig _config;

public Parent(IOptions<BrahBrahConfig> config)
{
    _config = config?.Value ?? throw new ArgumentNullException(nameof(config));
}

因此,在您startup.cs注册之后,你可以使用IOptions作为父类的构造参数,并使用这些设置在模型中设置相应的属性。


1
投票

使用依赖注入为你服务,而不是为你的模型。模型不应该有任何逻辑或服务注册。

如果你谈论的是服务类,它们通常是DI的一部分。你可以让DI自动解析在例如施工服务他们注册到DI。

例如,

public class Parent
{
    public Parent(IConfiguration configuration, ChildOne childOne, ChildTwo childTwo)
    {
        _configuration = configuration;
        _childOne = childOne;
        _childTwo = childTwo;
    }

    private IConfiguration _configuration;
    private ChildOne _childOne;
    private ChildTwo _childTwo;

}

如果您需要自己初始化ChildOne和ChildTwo,那么你就需要通过IConfiguration参数或至少的IServiceProvider,以解决所需的服务(S)

© www.soinside.com 2019 - 2024. All rights reserved.