Lets assume we have a class which will be widely used throughout the (c#) code, for example a Log class. Say the Log writes entries into XML files in a specific directory. Now one attempt to force the user to initialize the class with the required information would be to make the default (parameterless) constructor private and provide one which takes a logdirectory parameter. The drawback on this would be, that the user everytime something needs to be written to the log and thus an instance of the Log class is created, the parameter needs to be provided.
What other options are available? Thanks in advance for your replies.
Four options (mostly covered, but not explicitly and together):
Just make the calls static, and include static initialization. This is horrible for testing (of classes that depend on it) but very simple.
Use a singleton as suggested by most other answers. This is potentially better from a testing point of view (you could have internal methods to replace the singleton for test purposes only), and implement an interface for mocking purposes.
Use dependency injection: make everything that needs the dependency take it in a constructor or whatever, and get your DI framework to hook everything up. Much better from a testing perspective, but it’s not exactly convenient.
Use a factory – like the singleton, but separating the implementation from the construction. (It may effectively end up as a singleton, but without as many assumptions of that.)