Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

c# - How to access appsettings from another project

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": "[email protected]"
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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)
        {                         
        }
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...