Reputation: 1352
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?
Upvotes: 1
Views: 89
Reputation: 1038820
Since it's only the Init
method which requires an initializer it would make more sense to have this method take it as argument instead of using constructor injection:
class InMemoryDb
{
SomeBackingStore _store;
void Init(IInitialiser initialiser)
{
_store = initialiser.Initialise();
}
}
Then it is the responsibility of the caller of the Init method to provider the initializer. You could also use a boolean isInitialized
field which will indicate whether the Init
method was called. This field will be used by other methods that potentially rely on the _store
field to ensure that it is being properly initialized.
Upvotes: 2