was successfully added to your cart.

Why can’t I add a dependency to my UI in my class library?

Why can’t I add a dependency to my UI in my class library?

By March 9, 2018 Ask Tim No Comments

Avoiding Circular Dependencies in C#

When you are adding references in your project, it may seem natural to add a dependency both ways. That way the UI can know about the class library and the class library can know about the UI. However, this does not work (no, it is not a bug) as you can see in this demo:

Let’s first look at the practical reason for this. When you compile a Class Library project, it builds a dll file. It brings in all of the dll files it depends on and puts everything in the bin\Debug or bin\Release directory. When you compile a UI project, an exe file gets built. Again, it brings in all of the dll files it depends on and puts everything in the bin\Debug or bin\Release directory. So what’s the problem? Well, how does the UI bring in the dll for the Class Library if the Class Library is waiting to build until it has the UI’s exe? See the problem? The UI has to wait for the compiled Class Library but the Class Library has to wait for the compiled UI.

OK, so that is the practical reason. Now let’s look at the logical reason. If your Class Library depends on your user interface, why is it a separate project? Adding the dependency on the User Interface means that the Class Library cannot be used anywhere without the UI. Want to change out the UI for something different? Sorry, you have to redo the Class Library as well. This is called tight coupling. The two projects are interlinked in a way that they cannot be separated. At that point, you might as well put your code in your UI (which is not good).

To summarize, do not add a reference to your UI in your Class Library. To make things clearer, what I recommend is that you name your Class Library with the name “Library” at the end so that when you add a reference, you only ever select an item with “Library” in the name (this is one of my C# best practices: https://youtu.be/-9b8NRqjUFM?t=5m21s).

Leave a Reply