Reputation: 17527
ASP.Net 5 offers an options pattern to easily convert any POCO class into a settings class. Using this I can write my settings in json and then turn them into a typed object that I can inject into my controllers. So, for example, my ConfigureServices
method in Startup.cs
contains the line
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
and then this gets passed into my controllers' constructors using dependency injection
public ItemsController(IOptions<AppSettings> settings) { /* do stuff */ }
One of my controllers fires up a DNN to do some of its work. To reduce the cost of starting the DNN I do that from the static class constructor. Static constructors are parameterless and so I cannot pass in the required settings object, but I could set a static IOptions<AppSettings>
property on the ItemsController
from my ConfigureServices
method. How do I get at that? Where is the dependency injector and how do I persuade it to hand me an IOptions<AppSettings>
?
Upvotes: 2
Views: 1202
Reputation: 56869
I think you are looking at the problem wrong. The problem is that you have a static class and are using DI, not how to inject your dependencies into a static class (which cannot be done without resorting to a service locator or another hack).
Most DI containers have a singleton lifestyle, which allows you to share the same instance of an object across your application. Using this approach, there is no need for a static class. Eliminate the static class by replacing it with an singleton instance, and you have an avenue where you can inject dependencies into your constructor.
Upvotes: 5