user1496062
user1496062

Reputation: 1317

How to see if running under service fabric

I sometimes run projects locally out of visual studio is there a better way to detect if I'm hosted by SF rather than the exception. I can see possibly the path or entry assembly but there must be a better way.

try
{
    ServiceRuntime.RegisterServiceAsync("FisConfigUIType",
        context = > new WebHost < Startup > (context, loggerFactory, "ServiceEndpoint", Startup.serviceName)).GetAwaiter().GetResult();
    Thread.Sleep(Timeout.Infinite);
}
catch (FabricException sfEx)
{
    RunLocal(args, loggerFactory);
}

Upvotes: 16

Views: 2624

Answers (2)

spottedmahn
spottedmahn

Reputation: 15991

Check Service Fabric Environment Variables:

var sfAppName = Environment.GetEnvironmentVariable("Fabric_ApplicationName");
var isSf = sfAppName != null;

Source: from @mkosieradzki GitHub Issue

Upvotes: 22

user1496062
user1496062

Reputation: 1317

This is what i have come up with but something without an exception would be better (and note some projects use Core)

static bool IsSFHosted()
{
    try
    {
        FabricRuntime.GetNodeContext();
        return true;
    }
    catch (FabricException sfEx) when (sfEx.HResult == -2147017661 || sfEx.HResult == -2147017536 || sfEx.InnerException?.HResult == -2147017536)
    {
        return false;
    }
}

eg.

var isSFHosted = IsSFHosted();
var servicesPreRegister = builder.GetPreRegisterServicesForStore(node: node, security: false);

if (isSFHosted)
{
    ServiceRuntime.RegisterServiceAsync("DeliveriesWriteType",
        context => new WebAPI(context, loggerFactory, servicesPreRegister)).GetAwaiter().GetResult();
}
else
{
    loggerFactory.AddConsole();
    // run with local web listener with out SF
}

Upvotes: 5

Related Questions