ASP.NET: Check if run from migration

Viewed 2333

I have some code in my ConfigureServices that fails when running a migration:

dotnet ef migrations list

I'm trying to add a Certificate but it can't find the file (it works when starting the project as a whole). So is there a way to do something like this:

if (!CurrentEnvironment.IsMigration()) {
    doMyStuffThatFailsInMigration()
}

That way I could keep my code as it is but just execute it when not running it in a migration.

Thanks

2 Answers

Just set a static flag in the Main method (which is not called by the dotnet-ef tool):

public class Program
{
    public static bool IsStartedWithMain { get; private set; }

    public static void Main(string[] args)
    {
        IsStartedWithMain = true;
        ...
    }
}

and then check it when needed:

internal static void ConfigureServices(WebHostBuilderContext context, IServiceCollection services)
{
    if (Program.IsStartedWithMain)
    {
        // do stuff which must not be run upon using the dotnet-ef tool
    }
}
Related