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")); 解决方案 The "proper" wayRegister 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)Aspnet will do it's magic and inject the class there.The "nasty" wayIf 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 5 Docs in Dependency Injection 这篇关于控制器外部的ASP.NET 5 DI应用程序设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-18 20:35