StyletIoC Misc - canton7/Stylet GitHub Wiki

This page contains various other bits and bobs which deserve a mention, but aren't large enough to deserve their own page.

Circular Dependencies

Circular dependencies, except those of the type documented below, cause a StackOverflow exception. It isn't trivial to spot these ahead of time, and while a StackOverflow exception isn't ideal, it's not worth the complexity of avoiding it.

Parent/Child Circular Dependencies

Say you have something like this:

class Parent
{
   public Parent(Child child) { ... }
}

class Child
{
   public Parent Parent { get; set; }
}

where you want StyletIoC to be able to create an instance of Parent, or Child, and have the other created appropriately.

The trick is to use factories to create both, and not to use the container to resolve an instance of Child and creating a Parent, and vice versa. It's a bit messy, but then circular dependencies are messy anyway.

Child's Parent property must not have an [Inject] attribute on it, or the BuildUp step will cause a StackOverflow.

builder.Bind<Parent>().ToFactory(container =>
{
   var child = new Child();
   container.BuildUp(child); // If child requires any property injection
   var parent = new Parent(child);
   child.Parent = parent;
   return parent; // The parent will be automatically built up by StyletIoC
});
builder.Bind<Child>().ToFactory(container =>
{
   var child = new Child();
   var parent = new Parent(child);
   container.BuildUp(parent); // If parent requires any property injection
   child.Parent = parent;
   return child; // The child will be automatically built up by StyletIoC
});
⚠️ **GitHub.com Fallback** ⚠️