How to access appsettings from another project

2020-02-10 07:59发布

In the startup file I need a way to access IConfiguration in another project. I have been told the Business Logic should not know about IConfiguration. If thats the case then how do I inject data from appsettings down to the business logic projects.

appsettings.json

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

How would I access AdminEmail in a class library I created in the same solution?

3条回答
家丑人穷心不美
2楼-- · 2020-02-10 08:30

You can use Microsoft.Extensions.Configuration to achieve this. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?tabs=basicconfiguration

1 - Create a model for the settings

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

2 - Configure it on Startup.cs

services.Configure<AppSettings>(Configuration);

3 - Use DI in your class library to retrieve the settings

private readonly AppSettings _appSettings;

public MyClass(IOptions<AppSettings> appSettings)
{
    _appSettings = appSettings.Value;
}
查看更多
戒情不戒烟
3楼-- · 2020-02-10 08:36
  • Define a model for settings

    public sealed class EmailSettings
    {
        public string AdminEmail { get; set; }
    }
    
  • Configure settings

    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);
        }
    }
    
  • Inject and use it

    public class ClassLibraryInTheSameSolution
    {
        public ClassLibraryInTheSameSolution(EmailSettings emailSettings)
        {                         
        }
    }
    
查看更多
Lonely孤独者°
4楼-- · 2020-02-10 08:41

You could inject it quite easily:

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);
    }
}
查看更多
登录 后发表回答