Search code examples
c#.netvisual-studiowinformsshared-project

Windows forms references and singleton with conflicted imported type


I have a solution with the following projects:

  • Model: A shared project with the model
  • App1: A windows forms application
  • App2: Another windows forms application

I'm trying to move some UserControl currently duplicated in both projects in a common project, called CommonUI. So:

  • Model
  • CommonUI: Referencing Model
  • App1: Referencing Model and CommonUI
  • App2: Referencing Model and CommonUI

But this got me many warnings like:

The type 'AppState' in '[..]Model\AppState.cs' conflicts with the imported type 'AppState' in '[..]CommonUI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in '[..]Model\AppState.cs'

The problem is that AppState is a Singleton but it get duplicated, App1 see an instance and CommonUI see another instance has I now have 2 class called "AppState", one from the reference App1->Model and the other one from App1->CommonUI->Model.

What did I did wrong? Thanks


Solution

  • AppState is declared in Model which is a shared project. A shared project is not a class library. The source code in a shared project is compiled into each project that references it. In other words, if you have - say - 3 projects referencing the Model project, you will have declared the AppState class 3 times.

    The solutions are to convert Model into a class library, or move AppState somewhere else.

    In my experience, it is best to use Shared Projects only for small relatively inconsequential pieces of utility code which are to be built into an executable. Referencing them from libraries, or using them as libraries, is asking for trouble.