Sometimes I have classes that need to get some information to build. I'm not talking about references to other objects (which will be entered), but about (for example) strings that contain unique information:
// Scoped as singleton! class Repository { public Repository( InjectedObject injectedObject, string path ) { ... } }
How did you enter this line? One possibility is to write the Init() method and avoid the injection for the string:
class Repository { public Repository( InjectedObject injectedObject ) { ... } public void Init( string path ) { ... } }
Another possibility is to wrap information in an object that you can enter:
class InjectedRepositoryPath { public InjectedRepositoryPath( string path ) { ... } public string Path { get; private set; } } class Repository { public Repository( InjectedObject injectedObject, InjectedRepositoryPath path ) { ... } }
Thus, I need to create an instance of InjectedRepositoryPath during the initialization of my DI container and register this instance. But I need such a unique configuration object for each similar class.
Of course, I can enable RepositryFactory instead of the Repository object, so the factory will ask me for the path:
class RepositoryFactory { Repository Create( string path ) { ... } }
But then again, this is one factory only for a singleton object ...
Or finally, since the path will be extracted from the configuration file, I could skip the path around the line and read the configuration in my constructor (which is probably not so optimal, but possible):
class Repository { public Repository( InjectedObject injectedObject ) {
What is your favorite method? For non-Singleton classes, you should use imho to solve Init() or factory, but what about objects with a single scope?