Simple: provide an instance of the configuration to each library component in its constructor. That might be a little more verbose than you want, but it meets your design goal and it gives the library user complete freedom (maybe even to use a dependency injection library themselves).
Is there a better option than the Singleton pattern for exposing my classes' dependencies, if I'm not using an IoC container?
-
17-07-2023 - |
Frage
I am building a class library to be consumed by other applications. I do not have an IoC container as I do not wish to force it on the consumers of my library.
Consumers should be able to configure the library in their bootstrapper, as per this example:
Example.Configure({ x =>
{
x.AddSomeSetting();
x.AddAnotherSetting();
});
Any future use of the library should use this central configuration:
// exampleObject should use the central configuration defined above
var exampleObject = new Example.SomeClass();
I have used a singleton class to store the configuration, which is accessed by the rest of the library in future.
The problem comes when unit testing. As soon as a unit test method modifies the singleton configuration, all of the other unit tests are affected by this modification.
I could have a Reset()
method on the singleton that is called at the start of each test, but it would be there purely for the test.
Is there a better solution than storing this global state as a singleton?
Lösung