如何从另一个项目访问appsettings

时间:2018-02-23 13:25:28

标签: c# asp.net-core

在启动文件中,我需要一种方法来访问另一个项目中的IConfiguration。我被告知Business Logic不应该知道IConfiguration。如果是这样,那么我如何将数据从appsettings注入业务逻辑项目。

appsettings.json

{
  "AdminEmail": "myemail@gmail.com"
}

如何在我在同一解决方案中创建的类库中访问AdminEmail?

3 个答案:

答案 0 :(得分:5)

  • 定义设置模型

    public sealed class EmailSettings
    {
        public string AdminEmail { get; set; }
    }
    
  • 配置设置

    public sealed class Startup
    {
        private readonly IConfiguration configuration;
    
        public Startup(IConfiguration configuration) => this.configuration = configuration;
    
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .Configure<EmailSettings>(configuration)
                .AddSingleton(sp => sp.GetRequiredService<IOptions<EmailSettings>>().Value);
        }
    }
    
  • 注入并使用它

    public class ClassLibraryInTheSameSolution
    {
        public ClassLibraryInTheSameSolution(EmailSettings emailSettings)
        {                         
        }
    }
    

答案 1 :(得分:0)

你可以很容易地注射它:

public class EmailSettings
{
    public string AdminEmail { get; set; } // encapsulate as needed
}

public void ConfigureServices(IServiceCollection services)
{
    var settings = new EmailSettings
    {
        AdminEmail = Configuration["AdminEmail"]
    };

    services.AddSingleton(settings);
}

public class WhereverYouNeedThis
{
    private readonly EmailSettings _emailSettings;

    public WhereverYouNeedThis(EmailSettings emailSettings)
    {
        _emailSettings = emailSettings;
    }

    public void Use()
    {
        Debug.Log(_emailSettings.AdminEmail);
    }
}

答案 2 :(得分:0)

您可以使用Microsoft.Extensions.Configuration来实现此目的。 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?tabs=basicconfiguration

1 - 为设置创建模型

public class AppSettings 
{
    public string AdminEmail { get; set; }
}

2 - 在Startup.cs上配置

services.Configure<AppSettings>(Configuration);

3 - 在课程库中使用DI来检索设置

private readonly AppSettings _appSettings;

public MyClass(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings.Value;
}