我可以讓Docker/Linux保持我的.NET Core應用程序活着的唯一方法是欺騙ASP.NET來爲我託管它......這是一個很醜陋的黑客!
這樣做會在Docker中使用docker run -d
選項運行,因此您不必擁有實時連接來保持STDIN流的活性。
我創建了一個.NET的核心控制檯應用程序(不是一個ASP.NET應用程序)和我的計劃類看起來是這樣的:
public class Program
{
public static ManualResetEventSlim Done = new ManualResetEventSlim(false);
public static void Main(string[] args)
{
//This is unbelievably complex because .NET Core Console.ReadLine() does not block in a docker container...!
var host = new WebHostBuilder().UseStartup(typeof(Startup)).Build();
using (CancellationTokenSource cts = new CancellationTokenSource())
{
Action shutdown =() =>
{
if (!cts.IsCancellationRequested)
{
Console.WriteLine("Application is shutting down...");
cts.Cancel();
}
Done.Wait();
};
Console.CancelKeyPress += (sender, eventArgs) =>
{
shutdown();
// Don't terminate the process immediately, wait for the Main thread to exit gracefully.
eventArgs.Cancel = true;
};
host.Run(cts.Token);
Done.Set();
}
}
}
啓動類:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IServer, ConsoleAppRunner>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
}
}
的ConsoleAppRunner類
public class ConsoleAppRunner : IServer
{
/// <summary>A collection of HTTP features of the server.</summary>
public IFeatureCollection Features { get; }
public ConsoleAppRunner(ILoggerFactory loggerFactory)
{
Features = new FeatureCollection();
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
public void Dispose()
{
}
/// <summary>Start the server with an application.</summary>
/// <param name="application">An instance of <see cref="T:Microsoft.AspNetCore.Hosting.Server.IHttpApplication`1" />.</param>
/// <typeparam name="TContext">The context associated with the application.</typeparam>
public void Start<TContext>(IHttpApplication<TContext> application)
{
//Actual program code starts here...
Console.WriteLine("Demo app running...");
Program.Done.Wait(); // <-- Keeps the program running - The Done property is a ManualResetEventSlim instance which gets set if someone terminates the program.
}
}
關於它的唯一好處是你可以在你的應用程序中使用DI(如果你想) - 所以在我的用例中,我使用ILoggingFactory來處理我的日誌記錄。
來源
2016-11-11 13:56:58
Jay
我想了解自己:我認爲你要在交互模式下運行它,並可能要加上一個期限。 'docker run -it -name demo demo' – hdz
如果你在背景模式下運行它(-d),你也可以附加到它'docker attach {container}'來取回它。你不會看到輸出,因爲它已經輸出了,但你可以按回車鍵退出 – hdz