3

I'm using Ninject in a reasonably large project and want to utilize the Dependency Creation and Event Broker extensions.

The Dependency Creation readme gives the following example (although I believe InCreatorScope has possibly been renamed to InDependencyCreatorScope now)

this.kernel.Bind<IParent>().To<Parent>();
this.kernel.DefineDependency<IParent, Dependency>();
this.kernel.Bind<Dependency>().ToSelf().InCreatorScope();

This example creates a dependency via the container between Parent and Dependency without them having a "hard" reference to each other. This promotes loose coupling between the components and allows me to use Event Broker to publish an event on Parent and subscribe to it on Dependency, without explicitly wiring up an event handler.

My question is this: What if Dependency is injected into other objects and I want it to have RequestScope lifetime for standard activations? How do I state that I want to use Request scope for standard activations but dependency creator scope when created alongside Parent?

Matt B
  • 8,315
  • 2
  • 44
  • 65

1 Answers1

2

You can use conditional bindings:

// dedine dependency as before
this.kernel.Bind<Dependency>().ToSelf().When(r => r.Parameters.OfType<DependencyCreationParameter>().Any()).InDependencyCreatorScope();
this.kernel.Bind<Dependency>().ToSelf().When(r => !r.Parameters.OfType<DependencyCreationParameter>().Any()).InRequestScope();

But usually when you have an event broker based solution you can simply register the created objects with an OnActivation overload in the event broker which makes it easier then creating complex scopes.

Daniel Marbach
  • 2,294
  • 12
  • 15
  • Hi Daniel, thanks I was looking at doing something like this. What I really want to do is ensure that there is a one to one relationship between my publisher and subscriber. I had multiple subscription handlers firing and I couldn't work out how to ensure that the event broker was scoped just between Parent and Dependency and not any other Dependency objects that may be injected further down in the object graph. – Matt B Jan 16 '13 at 10:49