ASP.NET 5 DI app setting outside controller

后端 未结 4 986

I can DI app setting in the controller like this

 private IOptions appSettings;
 public CompanyInfoController(IOptions appS         


        
4条回答
  •  迷失自我
    2021-01-21 06:07

    The "proper" way

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

    services.AddTransient();
    

    (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, 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)
    

    Aspnet 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();
    

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

    Asp.Net 5 Docs in Dependency Injection

提交回复
热议问题