Search code examples
c#factory-patterncircular-dependency

Factory object causes stackoverflowexception due to dependancy upon itself


I have a c# factory object which creates objects through factory methods, using a list of objects as a source.

The list of objects is created like this:

public WidgetFactory()
    {
        widgetLibrary = new List<WidgetModel>();

        //Add all widgets
        widgetLibrary.Add(new ClientsWidget());
        widgetLibrary.Add(new InstallationsWidget());
        etc.

and various parts of my application access this list in different ways to get the type of object it needs.

But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.

How can I alter my design to accomodate this need?


Solution

  • But I now have a requirement that one of the objects in the list(i.e. a widget) needs to make use of the widget factory itself. Clearly this causes a circular reference.

    How can I alter my design to accomodate this need?

    Typically, objects should not rely on the factory that creates them for construction, as it causes exactly this problem. If you can push in the reference to the factory, but not use it until it's needed, it may solve the issue.

    If you absolutely need to do this, then the best approach may be to lazily instantiate the objects within the factory. Instead of having your WidgetFactory contain a List<WidgetModel> internally, you could use a List<Lazy<WidgetModel>>. This would allow the individual "widgets" to only evaluate as needed, which would mean that, when the widget in question tries to reference the factory, it'll be fully loaded.