asp.net-coredependency-injection

ASP.NET Core DI app setting outside controller


I can DI app setting in the controller like this

 private IOptions<AppSettings> appSettings;
 public CompanyInfoController(IOptions<AppSettings> appSettings)
 {
     this.appSettings = appSettings;
 }

But how to DI that in my custom class like this

  private IOptions<AppSettings> appSettings;
  public PermissionFactory(IOptions<AppSettings> appSetting)
  {
      this.appSettings = appSettings;
  }

my register in Startup.cs is

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

Solution

  • The "proper" way

    Register your custom class in the DI, the same way you register other dependencies in ConfigureServices method, for example:

    services.AddTransient<PermissionFactory>();
    

    (Instead of AddTransient, you can use AddScoped, or any other lifetime that you need)

    Then add this dependency to the constructor of your controller:

    public CompanyInfoController(IOptions<AppSettings> appSettings, PermissionFactory permFact)
    

    Now, DI knows about PermissionFactory, can instantiate it and will inject it into your controller.

    If you want to use PermissionFactory in Configure method, just add it to it's parameter list:

    Configure(IApplicationBuilder app, PermissionFactory prov)
    

    ASP.NET will do it's magic and inject the class there.

    The "nasty" way

    If you want to instantiate PermissionFactory somewhere deep in your code, you can also do it in a little nasty way - store reference to IServiceProvider in Startup class:

    internal static IServiceProvider ServiceProvider { get;set; }
    
    Configure(IApplicationBuilder app, IServiceProvider prov) {
       ServiceProvider = prov;
       ...
    }
    

    Now you can access it like this:

    var factory = Startup.ServiceProvider.GetService<PermissionFactory>();
    

    Again, DI will take care of injecting IOptions<AppSettings> into PermissionFactory.

    ASP.NET Core Documentation page on Dependency Injection