dependency-injectionunity-containeraopunity-interceptionpolicy-injection

Unity Interception and classes with Circular Reference


My rich domain model has some circular reference, and this is intentional.

I am also writing my own ORM for more control, and to detect changes made to properties I am using Unity to intercept any call to setters and trigger the property change notification (similar with how EF works).

The problem is that I'm getting Stack Overflow, because the policy interception is going over the same object, over and over again. Is there a way to make it do reference counting?

I have already made sure that the constructor aren't circularly dependent, but I still need Policy Injection to stop recursing over the same objects repeatedly.


Solution

  • Instead of injecting the objects, you can inject the functions to built them, when you have a circular reference:

       Container.RegisterType<IMyService, ImplService>(... );
    
    
       public class MyClass {
    
          private Func<IMyService> _serviceProvider;
    
          public MyClass(Func<IMyService> serviceProvider) { _serviceProvider = serviceProvider        }
    
          public void DoStuff() {
             _serviceProvider().DoSomething();
          }
    
       }
    

    Unity will inject a function that returns IMyService