Let's assume that we have a service that needs to be initialized, but then it's a singleton. For example, something like this:
public interface IGraphsContainer
{
void Initialize(IEnumerable<Graph> initialContent);
void Add(Graph graph);
bool Contains(Graph graph);
IEnumerable<Graph> FindAll(Criteria complexCriteria);
}
Assume that the implemention has no dependencies. So it can be easily binded in a DI container and auto-injected into classes that need it.
This works for me, expect for the fact that I must not forget to initialize the container before using it. It needs some additional code to prevent this. That's why I am not enterily satisfied.
Is there a better solution for this that doesn't require the Initialize method?
EDIT: I was not clear about the singletion. The fact is, it's a singleton in its scope, which is NOT the application scope. Therefore this initialize method is invoked in some other AbstractFactory.
In this case, if Graphs are pulled from a folder and a user decides to change the folder, then we need to change the graphs based on that folder and thereby the initial containers content.
Here's the real example where I'm using this Initialize approach. The underlying algorithm is pretty complex and this is just a half of it. So far I need 3 things to be initialized like this.
initialize
can be called to initialize without the abstraction.Initialize
on them? The ideal solution is to avoid singletons, but if you insist, if you need to initialize these singletons and do the DI before they can be used, then just keep the singleton object references at null initially and just construct them withnew SingletonType(initialContent)
when you can meaningfully do so. Give the singletons a constructor which accepts the DI content as a parameter instead of relying on thisInitialize
method.GeneratorFactory
can't receive the generator input in its own constructor? If so, it could pass it along to the constructors of everything else it constructs there.