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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top