//pull config from config file, then pass in to class
public class SomeClass(string connectionString, string
The rest of your answer talks about DI, but this particular snippet isn't really DI-oriented. This is a normal run-of-the-mill parametrized constructor.
I do wonder about
someOtherRequiredConfiguration. Based on the name, I'm going to assume you've oversimplified the example and that the real code contains meaningful parameters.
public class SomeClass()
//Do work to pull from config file in constructor or in parameter
the class is responsible for retrieving the configuration it cares about
Objectively correct, but that doesn't answer whether it's a good idea or not. I will elaborate on this point.
I think the second way makes DI much easier
Quite the opposite. What you've done here is removed the option to configure your class the way you want to. This makes it harder to mock, not easier. You're forcing yourself to create a new (probably derived) class whenever to you want to test against a different external resource (= different connectionstring).
You could have an
IConfigRepository or something if you wanted to control that separately.
What you say isn't wrong, but I just want to reframe what you said: your proposed solution now requires you to create an
IConfigRepository before you can properly test. It's not impossible to do so, but it creates more work to have testable code, which is the opposite of what DI tries to achieve (increasing testability)
But pulling the config values and passing them in at the composition root feels wrong to me.
The fact that you refer to
SomeClass as a composition root makes me suspect that you're thinking about DI/testability in an unusual way.
The value of a parameter (connectionstring) has little to do with dependency injection. Dependency injection focuses on stitching together custom classes in a way that you can easily separate them in the future (e.g. testing a single component, or swapping a particular component for another one).
Should a class be responsible for its own configuration?
It highly depends on the configuration you're focusing on. Some things don't belong in a config file to begin with and can simply be set as a
If you can guarantee that
SomeClass will always use a particular config key, without fail, then you can retrieve the key from inside the class (constructor or otherwise).
SomeClass needs to be able to toggle between several connectionstrings (e.g. an application that uses multiple databases at the same time), then it needs to be configurable. A constructor parameter is the better approach here.