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

Categories

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?

See Question&Answers more detail:os

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...