Pregunta

I am just starting to use Ninject on a (large) project and am wading in by only using DI for a portion of it to start. I have a subsystem that is organized using constructor injection extensively. Using Ninject to inject all of the dependencies between classes in this subystem is working great. However, I have dependencies on things outside of the subystem that I would really like to use Ninject to automatically inject as well, but not to be in charge of their lifecycle.

I thought Bind<T>.ToConstant(...) would work for what I am trying to do. For instance, I may have a class of type Monkey that is to act as a Singleton, but another part of my application is handling its lifecycle without Ninject (for example, creating it and disposing it manually). When my Ninject-equipped subsystem gets created I instantiate a kernel, bind my subsystem classes, and then use something like Bind<Monkey>.ToConstant(Monkey.Instance) to bind to various "external" dependencies. This works great at activation time but does not work as needed when I dispose the kernel. My subsystem can have a shorter lifecycle than these external dependencies, but when I call Dispose on the kernel all of these dependencies get disposed, which is not what I want. While I can see arguments both ways, it seems a bit questionable that Ninject would automatically dispose an object that it did not create. I'm hoping there is at least a way to opt out of this behavior, but so far I have not found anything. Is there any support for this?

¿Fue útil?

Solución

Add InTransientScope to your constant object.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top