0

I don't have much exprience with unity so I may be doing something wrong. I am using 3 interfaces: A and B, and C.

B depends on A.

C depends on both A and B.

For some reason, Unity creates 2 different instances of A - one for C and one for B, instead of creating only one instance that both C and B would use. What could be the cause for this? I should add that B is registered using HierarchicalLifetimeManager and A is defined without a LifetimeManager.

Thanks in advance

Tsahi
  • 11
  • 1
  • Unity, and basically all DI containers, treat every "service" (which is the type/name/interface you register your instance with) as a different object. I don't know Unity enough to give you an answer, but [this question](https://stackoverflow.com/questions/1394650/unity-register-two-interfaces-as-one-singleton) (and its answers) should help guide you in the right direction – Jcl May 12 '22 at 11:50
  • be careful all A B C are in the same "Container" – user2147873 May 12 '22 at 11:58
  • you can chose the scope of the instance you share by specifying an additional parameter in RegisterInstance. per default, instances are shared per container, if you want it as Singleton, then specify as extra parameter Singleton. that guy => public static IInstanceLifetimeManager Singleton { get; } – user2147873 May 12 '22 at 12:00
  • You should specify the per resolve lifetime when registering the A service. – Lasse V. Karlsen May 12 '22 at 12:38
  • Side question: Does it matter? Does your service have state? – Lasse V. Karlsen May 12 '22 at 12:39
  • A is registered in a parent container and B in a child container. C is not registered. Yes, the service has a state – Tsahi May 12 '22 at 12:42

0 Answers0