如何查看是否在服务结构下运行

时间:2016-09-30 00:10:23

标签: c# azure-service-fabric

我有时在Visual Studio中本地运行项目是否有更好的方法来检测我是否由SF托管而不是异常。我可以看到路径或入口组件,但必须有更好的方法。

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);
}

2 个答案:

答案 0 :(得分:12)

检查Service Fabric Environment Variables

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

来源:来自@mkosieradzki GitHub Issue

答案 1 :(得分:5)

这是我提出的,但没有例外的事情会更好(并注意一些项目使用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;
    }
}

例如

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
}