_container.RegisterType<TypeA>();
_container.RegisterType<TypeC>(); // TypeC has a dependency to TypeA
_container.RegisterType<TypeD>(); // TypeD has a dependency to TypeA
_container.RegisterType<TypeE>(); // TypeE has a dependencies to TypeC and TypeD
_container.RegisterType<TypeF>(); // TypeF has a dependencies to TypeC and TypeD
How do I set this up so that when I create types E and F they both use a new instance of TypeA (indirectly through types C and D) but C and D both use the same TypeA?
If it helps imagine that TypeA is a repository and C and D are services that use that repository. Types E and F are ViewModels that need different repositories but interact with the repository through services C and D.
I imagine I could resolve typeA and then use that instance to resolve the other types but I’m guessing there is a better way, as that seems quite messy.
Take a look at my answer to your second question here.
By using a
PerResolveLifetimeManager, whenTypeEis resolved,TypeEand its dependenciesTypeCandTypeDall get the same instance ofTypeA. WhenTypeFis resolved, a newTypeAis resolved, which it and all of its dependencies will share.PerResolveLifetimeManageris one of my favorite things about Unity as an IOC container over others.