Let’s say I have the following classes that I want to construct using Ninject, with the arrows showing dependencies.
A > B > D
A > C > D
I want to configure Ninject such that A is transient scoped, i.e. every time you ask Ninject for an A, you get a new one. I also want B and C to be transient, you get a new one of those every time you ask for an A. But I want the D to be reused across both B and C. So every time I request an A, I want Ninject to construct one of each object, not two Ds. But I don’t want Ds to be reused across different As.
What is the best way to set this up using Ninject?
Update:
After some more research, it seems like Unity has a PerResolveLifetimeManager which does what I’m looking for. Is there a Ninject equivalent?
Ninject supports four built in object scopes out of the box: Transient, Singleton, Thread, Request.
So there isn’t any
PerResolveLifetimeManagerlike scope but you can implement it easily with registering a custom scope with theInScopemethod.As it turned out there is an existing Ninject extension:
ninject.extensions.namedscopewhich provides theInCallScopemethod which is what you are looking for.However if you want to do it yourself you can do with a custom
InScopedelegate. Where you can use the mainIRequestobject for the typeAto use it as the scope object:Where the sample classes are: