IMK
IMK

Reputation: 718

Enabling conditional compilation directives based on the references included in a C# Project

I have ProjectA and ProjectB. ProjectA can work independently without any dependency of ProjectB. Now, I like to enable some modules/features in ProjectA only if the ProjectB is added as a reference in ProjectA. How to achieve this?

I have tried by adding conditional compilation in the needed modules/features in ProjectA like below.

#if ProjB
{
..
}
#endif

But how can I enable these conditional compilation constants by checking a condition that the "ProjectB" is referenced to "ProjectA". Also, I do not need "ProjectB" to be referenced always in "ProjectA". Still the "ProjectA" need to work independently in some cases.

Upvotes: 1

Views: 53

Answers (1)

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

You can use something like Plugin pattern. E.g.:

  1. ProjectA loads and figures out if it has or not possibility to load ProjectB
  2. If ProjectB is available ProjectA looks for a well defined entry point (e.g. you can have one class implementing IPlugin with Load method
  3. If the entry point is found, the ProjectA calls it and stores the reference (some kind of variable or adds it to List if you have multiple options.
  4. Now in all places where you want your conditional compilation you just check if this Plugin exists and throw an exception that you need to add ProjectB in order to use this functionality.

You can define a special interface (multiple interfaces) that both projects will know about. Then your plugin (ProjectB) will provide this interface with all the methods that you want to call.

Upvotes: 1

Related Questions