Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 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 Reply

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)
        {                         
        }
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...