Preventing/getting around circular dependency problems

From OpenPetra Wiki
Revision as of 13:27, 2 April 2012 by Christiankatict (talk | contribs) (Created page with '==Introduction== This page that describes the '''recommended way''' of preventing/getting around circular dependency problems on the server side of OpenPetra. The approach descri…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

This page that describes the recommended way of preventing/getting around circular dependency problems on the server side of OpenPetra. The approach described would work for the client side as well, it is just not implemented yet in the sense that a specific Assembly is responsible for solving the circular dependency issue. Delegates are already used on the Client side for other reasons, though.

The Problem

A Method resides in Assembly 'A' and it needs to call a Method that resides in Assembly 'B'. This is fine as long as there is no code at all in Assembly 'B' that requires a Reference to be added to Assembly 'B' that references Assembly 'A' - this would create a 'circular dependency', i.e. Assembly 'A' would reference Assembly 'B' and Assembly 'B' would in turn reference Assembly 'A'. Such referencing creates a problem for the C# compiler as it cannot compile Assembly 'A' without Assembly 'B' to be built before and it can't build Assembly 'B' without Assembly 'A' to be built before; and therefore neither Assembly can be built (the 'chicken and egg problem').

Note: A circular dependency can also be much trickier as the dependency circle can involve several Assemblies that have Assembly References pointing only one way (and that is fine) but the last Assembly then has a Reference back to the first Assembly, therefore closing the circle and introducing a circular dependency. The C# compiler will find that out and refuse compilation.


The Solution

While there are several solutions to solving circular dependency, some are more preferred than others for reasons that I can't describe here in full (complexity and missing compile-time checks are some of the reasons that make certain solutions less preferred).

A solution that involves a rather low complexity and that allows for compile-time checks is the use of C# Delegates. The set-up of a Delegate that points to a Method in an arbitrary OpenPetra Server DLL and that will not cause a circular dependency is described in the following sections.