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

use*_*062 12 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);
}
Run Code Online (Sandbox Code Playgroud)

spo*_*ahn 12

检查服务结构环境变量:

var sfAppName = Environment.GetEnvironmentVariable("Fabric_ApplicationName");
var isSf = sfAppName != null;
Run Code Online (Sandbox Code Playgroud)

来源:来自@mkosieradzki GitHub Issue

  • 这应该被赞成,它还具有在条目库中没有依赖项的好处。 (2认同)
  • 正确答案! (2认同)

use*_*062 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

例如.

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
}
Run Code Online (Sandbox Code Playgroud)