Search code examples
asp.netasp.net-mvcdependency-injectionstructuremapstructuremap3

Set a StructureMap Nested Container to resolve unique object instances by default


According to StructureMap's documentation the default behavior of containers is that a Parent Container resolves a new object instance each time one is requested and Nested Containers resolve the same object instance.

In 99% of cases this is fine - however I'm keen to know if there's a way I can set a nested container to behave similarly to the Parent Container and resolve new object instances by default - without the need to rely on the .AlwaysUnique() method.

Is this possible or is .AlwaysUnique the only way to do it on an object by object basis?


Solution

  • I think that beside explicit specification of nested container configuration there is no support for that as it was designed around creating temporary context for objects resolution. IIRC in SM 3.0 HttpContextScoped lifecycle was implemented with usage of nested container.

    If you want to have the flexibility of resolving existing object from the container or creating a new one you can implement factory that would handle it for you through injected context into the factory or based on explicit method call (factory.Create() or factory.ReuseIfExistsOrCreate()).

    Hope this helps!