Injecting options objects directly
The only negative point about the .NET Options pattern is that we must tie our code to the framework’s interfaces. We must inject an interface like IOptionsMonitor<MyOptions>
instead of the MyOptions
class itself. By letting the consumers choose the interface, we let them control the lifetime of the options, which breaks the inversion of control, dependency inversion, and open/closed principles.
We should move that responsibility out of the consumer up to the composition root.
As we explored at the beginning of this chapter, the IOptions
, IOptionsFactory
, IOptionsMonitor
, and IOptionsSnapshot
interfaces define the options object’s lifetime.
In most cases, I prefer to inject MyOptions
directly, controlling its lifetime from the composition root, instead of letting the class itself control its dependencies. I’m a little anti-control-freak, I know. Moreover, writing tests using the MyOptions
class...