Export (0) Print
Expand All

Circular References with Dependency Injection

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

The latest Unity Application Block information can be found at the Unity Application Block site.

Dependency injection mechanisms carry the risk of unintentional circular references, which are not easy to detect or prevent. This topic describes the situations where you may inadvertently cause circular references to occur, resulting in a stack overflow and application error. The most common causes of circular references with dependency injection are the following:

  • Objects generated through constructor injection that reference each other in their constructor parameters
  • Objects generated through constructor injection where an instance of a class is passed as a parameter to its own constructor
  • Objects generated through method call injection that reference each other
  • Objects generated through property (setter) injection that reference each other

For example, the following code shows two classes that reference each other in their constructors.

public class Class1
{
  public Class1(Class2 test2)
  { ... }
}

public class Class2
{
  public Class2(Class1 test1)
  { ... }
}

It is the responsibility of the developer to prevent this type of error by ensuring that the members of classes they use with dependency injection do not contain circular references.


Show:
© 2014 Microsoft