I'm working on a little light weight Dependency resolver found here


Currently if you do

var instance = container.Get<Foo>();

You get a new instance for each call to Get

This is correct when in a transient lifetime management. But what's the expected behavior when using constructor injection?

Lets say you have this chain of dependency, with constructor arguments

ClassOne ( ClassTwo, ClassThree )

ClassTwo ( ClassThree )

Now we do a container.Get<ClassOne>(); Should ClassThree be same for both ClassOne and ClassTwo?

edit: The question is what do you think most users expect the behavior of transient life time to be when coupled with constructor injection during one call to Get<T>.

edit: Both Ninject, Castle and Unity seems to create new instances so probably the thats the way it should work (And thats the way its working right now)

edit: hmmm. interesting StructureMap actually reuses the instance, here is a the output from a test I did (Numbers are hashcodes)

Ninject.StandardKernel 65778530 34340385

Microsoft.Practices.Unity.UnityContainer 9874138 2186493

Castle.MicroKernel.DefaultKernel 27253481 44856655

StructureMap.Container 14259084 14259084

Code to test above http://pastebin.com/xPpgupU1

edit: Actually if you do not specify .LifestyleTransient() castle will default to the same behavior as StructureMap, meaning it will be same instance per Resolve


1 Answer 1


The obvious, albeit obnoxious answer, would of course be "it depends"... ;)

Most of the resolvers in the "major" IoC containers out there allow you to specify this when defining the resolution schema. In Castle Windsor, for instance, you can define the lifetime as Singleton, Transient, Bound, Thread, ... (there is a bunch). Your example is a pretty clear cut "Bound" instance, IF ClassThree is a repository class. (Otherwise, it is of course not as clear cut.)

To elaborate, the real question is whether, in your example, the ClassOne and ClassTwo instances actually need to have access to the same instance of ClassThree, or if they in fact must have separate instances.

Ultimately, I think this is up to the user of the resolver as there is no real way to know if an arbitrary class should live or die. My suggestion would be to decide on a default implementation (I would choose transient) but provide support to modify the lifestyle accordingly.

  • The question only relates to transient scopes, in a singleton scope the reference should be same offcourse. See update
    – Anders
    Apr 14, 2015 at 8:58
  • See last edit, one of the Major players is not behaving like the rest
    – Anders
    Apr 14, 2015 at 10:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.