I have a class that is managed by ninject as a singleton that looks roughly like this:
class InMemoryDb
{
IInitialiser _initialiser;
SomeBackingStore _store;
InMemoryDb(IInitialiser initialiser)
{
_initialiser = initialiser;
}
void Init()
{
//once init'd i don't care what happens to the _initialiser field
_store = _initialiser.Initialise();
}
}
I have the IInitialiser suppied via Ioc (actually everything is container managed). My problem is, once initialised, the _initialiser object is never garbage collected (and why would it, given it is techinically still being referenced by the InMemoryDb singleton object) and it sits in the application consuming memory (it is upwards of 5gig). How can I cleanly structure my code, so that my objects are still wired up via Ioc, and disposed of after use. Essentially once it is initialised, I can be certain that its safe to dispose the object.
Unfortunately, I have so far resorted to:
void Init()
{
_store = new Initialiser().Initialise();
}
This will eventually get cleaned up by the GC as it is out of scope once the Init() method finishes executing, but it makes my code untestable and has a smell about it. I also thought of doing:
void Init()
{
_store = SericeLocator.Get<IInitialiser>().Initialise();
}
But again, this isn’t ideal as it polutes my code with a ServiceLocator call.
Any suggestions on how to structure this better?
Since it’s only the
Initmethod which requires an initializer it would make more sense to have this method take it as argument instead of using constructor injection:Then it is the responsibility of the caller of the Init method to provider the initializer. You could also use a boolean
isInitializedfield which will indicate whether theInitmethod was called. This field will be used by other methods that potentially rely on the_storefield to ensure that it is being properly initialized.