by proikan · 2y ago · 0 comments
Config config;
// production
config_from_file(&config, "config.json");
run_production_stuff(&config);
// unit tests
Config config;
config_from_memory(&config, &some_test_values);
run_tests(&config);So let's say you have a service FooService that requires some configuration.
( Ignoring the System.configuration namespace for now)
You'd have:
class FooService(IConfigurationService ConfigurationService){
// Access Configuration Through IConfigurationService
}
Then elsewhere you'd set up your DI framework to inject your ConfigFileService to satisfy IConfigurationService in prod.Yes, it can sometimes feel a bit like "turtles all the way down", where sometimes you just wish you had a bunch of concrete implementations.
In unit tests, you'd auto-mock IConfigurationService. For integration tests you might provide a different concrete resolution.
There are some advantages to service based DI though. The standard ASP.NET DI framework makes it trivially easy to configure it as a singleton, or per-request-lifetime, or per-instantiation, without having to manually implement singleton patterns.
This gives you good control over service lifetime.
But I just wanted to illustrate idiomatic .NET DI, and on reflection picking configuration was probably the worst way to illustrate it.