Is there a better option than the Singleton pattern for exposing my classes' dependencies, if I'm not using an IoC container?

StackOverflow https://stackoverflow.com/questions/23519360

質問

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?

役に立ちましたか?

解決

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).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top