当我想作为独立的 kestrel 在本地运行时,我将 Program.cs 替换为以下通用主机(对于 dotnet core 3.1+)
public static class Program
{
public static void Main(string[] args)
{
Host
.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>())
.Build()
.Run();
}
}
如果您正在使用某些做法,例如配置服务结构应用程序以读取 appsettings 等,这可能就足够了,就像我正在做的那样。 Startup.cs 是一样的,所以 IoCC 注册和托管服务是一样的。
我必须确保我的 Service Fabric 服务尽可能标准的唯一一点特别之处是:
在主服务中(例如:无状态服务)
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new ServiceInstanceListener[]
{
new ServiceInstanceListener(serviceContext =>
new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
return new WebHostBuilder()
.UseKestrel()
.UseCommonConfiguration() //this is custom
.ConfigureServices(
services => services
.AddSingleton<StatelessServiceContext>(serviceContext))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseUrls(url)
.Build();
}))
};
}
注意UseCommonConfiguration() 扩展是:
public static class WebHostBuilderExtensions
{
public static IWebHostBuilder UseCommonConfiguration(this IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
config.AddUserSecrets(appAssembly, optional: true);
}
});
return builder;
}
}
我想找到一种干净的方法来交换 Program.cs,具体取决于我是作为启动运行 Web 应用程序,还是作为启动运行包含服务的 Service Fabric 应用程序。