1

I am working to build C# Web Application. My Web Application can be deployed on Azure as well as on AWS.

Challenge is like my application needs Blob storage like Azure Blob and AWS S3.

Now I am using Repository pattern for now and I have added Azure SDK as well as AWS SDK.

But requirement is like to build 2 images so that image for Azure should have Azure SDK and Image for AWS should have AWS SDK only.

Is there any specific approach to tackle such scenarios?

In C++, we have compiler flag so that we can skip some portion of code from compilation. Is there any such option available in C# while compiling code to IL.

Note: If yes, then I will like to use 2 flags so that build one code for Azure and another for AWS.

xs2tarunkukreja
  • 446
  • 3
  • 8
  • I think you might be after [preprocessor directives](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives). – Shazi Mar 07 '23 at 16:12

1 Answers1

0

You could do this by defining custom constants, see msbuild, defining Conditional Compilation Symbols and others.

Create three class libraries:

  • YourLib.Abstractions: storage interfaces
  • YourLib.AWS: implementations for AWS
  • YourLib.Azure: implementations for Azure

Then your main application, in the .csproj, conditionally include references:

<ItemGroup>
   <ProjectReference Include="../YourLib.Abstractions/YourLib.Abstractions.csproj" />
</ItemGroup>

<ItemGroup Condition="$(DefineConstants.Contains('AWS_BLOBS'))">
   <ProjectReference Include="../YourLib.AWS/YourLib.AWS.csproj" />
</ItemGroup>

<ItemGroup Condition="$(DefineConstants.Contains('AZURE_BLOBS'))">
   <ProjectReference Include="../YourLib.Azure/YourLib.Azure.csproj" />
</ItemGroup>

And in your code, call the appropriate dependency injection logic:

#if AWS_BLOBS
services.AddAwsBlobs();
#endif

#if AZURE_BLOBS
services.AddAzureBlobs();
#endif

Then when compiling:

dotnet build /p:DefineConstants="AWS_BLOBS"

You can also create solution-level build configurations ("Debug: AWS", "Debug: Azure") and define the constants there.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272