ASP.NET 5 DI app setting outside controller

后端 未结 4 988

I can DI app setting in the controller like this

 private IOptions appSettings;
 public CompanyInfoController(IOptions appS         


        
4条回答
  •  时光取名叫无心
    2021-01-21 06:00

    You can do dependency injection in your non-controller classes as well.

    In your startup class,

    public class Startup
    {
      public IConfigurationRoot Configuration { get; set; }
    
      public Startup(IHostingEnvironment env)
      {
            // Set up configuration sources.
         var builder = new ConfigurationBuilder()
                 .AddJsonFile("appsettings.json")
                 .AddEnvironmentVariables();
         Configuration = builder.Build();
      }
      public void ConfigureServices(IServiceCollection services)
      {
         // register other dependencies also here
         services.AddInstance(Configuration);     
      }
    }
    

    Now in your custom class, Have the constructor accept an implementation of IConfiguration

    private IConfiguration configuration;
    public PermissionFactory(IConfiguration configuration)
    {
      this.configuration = configuration;
    }
    public void SomeMethod()
    {
      var someSection = this.configuration.GetSection("SomeSection");
      var someValue= this.configuration.Get("YourItem:SubItem");
    }
    

提交回复
热议问题