I've recently "discovered" the IoC realm, and decided to refactor a project I'm working on to use such a container.
To be specific - I'm using autofac in C#, in a .NET Core console application.
The program reads some configuration at startup, doesn't really matter how, just that it's all wrapped nicely with interfaces, especially an IConfigurationReader
which reads it and returns a matching class.
There are many possible configurations, each has its own class (e.g. NetConfig
for, well, network configuration), but eventually they're all part of a main AppConfig
- As properties.
Reading the configuration should be the first thing the program does, then it should pass some of the configurations to other aspects of the system for further processing.
Let's focus on NetConfig
for now.
Up till now, aspects of the system that require NetConfig
were accepting it as a concrete class, but there are a few problems with it:
- It's bad design when living in a DI-Aware system. Would be better to accept a Provider instead.
- I need to share the same configuration instance between all those modules that require it, similarly to a Singleton (Wouldn't implement one of course). A concrete provider, implementing the one suggested above, would be a nice & clean solution to this.
All right, say I've changed all NetConfig
-dependent modules to accept an INetProvider
instead.
A Singleton-like implementation of this provider should somehow provide the NetConfig
, that's its purpose after all, but it can't do that without getting it from somewhere else first, e.g. as a ctor parameter.
Problem is, that this NetConfig
instance is only created at runtime, reading it from some external source, so when registering with an IoC container, the NetProvider
can't be registered as there's no NetConfig
yet.
What should I do to resolve it? I've read many of the docs of autofac but it seems like none of their examples solve anything like this.