JankoHrasko
JankoHrasko

Reputation: 93

Can Ninject create standalone object?

I need to instantiate an object that no other object needs to reference and I want it to live as long as application is running. It will be using other services but no one else needs it's services.

Is it possible to let ninject create one such object at the beginning and maintain it in the memory for me or do I need to store it somewhere? How can I setup ninject to that it will create my instance and hold it until exit?

If so, what is your opinion on this practice?

Upvotes: 0

Views: 220

Answers (1)

BatteryBackupUnit
BatteryBackupUnit

Reputation: 13223

As far as i know, ninject does not provide such functionality out-of-the-box. However, when you doo

IBindingRoot.Bind<FooService>().ToSelf().InSingletonScope();

and then one single get:

IResolutionRoot.Get<FooService();

that's enough to make ninject keep the same object alive until the kernel is disposed. You don't need to keep a reference.


You could also use the DependencyCreation Extension to tie the lifetime of the FooService to another service/object.

Like so:

IBindingRoot.Bind<SomeSingletonWhichIsInstantiatedAtTheBeginning>().To<...>();
IBindingRoot.DefineDependency<SomeSingletonWhichIsInstantiatedAtTheBeginning, FooService>();
IBindingRoot.Bind<FooService>().ToSelf().InDependencyCreatorScope();

This results in FooService being instatiated when SomeSingletonWhichIsInstantiatedAtTheBeginning is instantiated and also "disposed" of when SomeSingletonWhichIsInstantiatedAtTheBeginning is disposed/unreferenced.

However, beware of circular dependencies!


Yet another way would be to use the OnActivation feature to achieve something equivalent to what was done before:

IBindingRoot.Bind<FooService>().ToSelf().InSingletonScope();

IBindingRoot
     .Bind<SomeSingletonWhichIsInstantiatedAtTheBeginning>()
     .To<...>()
     .OnActivation((context, service) => ctx.Kernel.Get<FooService>());

This ties the instantiation of FooService to the instantiation of SomeSingletonWhichIsInstantiatedAtTheBeginning and gets rid of FooService when the kernel is disposed.

Upvotes: 1

Related Questions