Docker 容器中的 .net Core 控制台应用程序抛出 System.ObjectDisposedException

.net Core Console application in Docker Container throws System.ObjectDisposedException

我找到了很多关于这个问题的条目,但没有一个解决方案适合我。

简而言之,我有一个 .net Core 3.1 控制台应用程序,我想在 Docker 中 运行。如果我在 Visual Studio 中或通过命令行启动应用程序,一切正常(调试和发布构建)。

如果我把它放在 Docker 容器中,我会得到以下异常:

Unhandled exception. System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)

我的 Program.cs 看起来像这样:

using System;
using System.Runtime.Loader;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;

namespace testapp
{
    internal class Program
    {
        private static IServiceProvider _serviceProvider;

        private static void Main(string[] args)
        {
            Startup.Init(out _serviceProvider);

            var ended = new ManualResetEventSlim();
            var starting = new ManualResetEventSlim();

            var dataStorage = _serviceProvider.GetService<IDataStorageService>();

            AssemblyLoadContext.Default.Unloading += ctx =>
            {
                Console.WriteLine("Unloding fired");
                starting.Set();
                Console.WriteLine("Waiting for completion");
                ended.Wait();
            };

            Console.WriteLine("Waiting for signals");
            starting.Wait();

            Console.WriteLine("Received signal gracefully shutting down");
            Thread.Sleep(5000);
            ended.Set();
        }

    }
}

还有我的Startup.cs

using System;
using System.Collections.Specialized;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Sinks.Elasticsearch;

namespace testapp
{
    public static class Startup
    {
        public static void Init(out IServiceProvider serviceProvider)
        {
            Injection(out serviceProvider);
        }

        private static void Injection(out IServiceProvider serviceProvider)
        {
            var builder = new HostBuilder()
                .ConfigureServices((hostContext, services) =>
                {

                    services.AddSingleton<IDataStorageService, DataStorageService>();


                    services.AddLogging(configure => configure.AddSerilog());
                }).Build();

            serviceProvider = builder.Services;

            var configService = serviceProvider.GetService<IConfigService>();

            Console.WriteLine("ElasticUrl: " + configService.GetElasticEndpoint());

            Log.Logger = new LoggerConfiguration()
                .Enrich.FromLogContext()
                .WriteTo.File("consoleapp.log")
                .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(configService.GetElasticEndpoint()))
                {
                    AutoRegisterTemplate = true,
                    TypeName = "_doc",
                    ModifyConnectionSettings = c => c.GlobalHeaders(new NameValueCollection
                        {{"Authorization", configService.GetElasticAuthentication()}})
                })
                .CreateLogger();

            builder.RunAsync();
        }
    }
}

在 Program.cs 的这一行抛出异常:

var dataStorage = _serviceProvider.GetService<IDataStorageService>();

在 Startup.cs 行 var configService = serviceProvider.GetService<IConfigService>(); 有效。

正如我所提到的,一切都在 运行 中并在 visual Studio 中工作,或者如果我在 CLI 中启动命令行工具。 仅在 Docker 中发生异常。 这是 Docker 文件:

FROM mcr.microsoft.com/dotnet/core/runtime:3.1

COPY bin/Release/netcoreapp3.1/publish/ app/

ENV TZ=Europe/Berlin
ENV ASPNETCORE_ENVIRONMENT=Production

RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

ENTRYPOINT ["dotnet", "app/testapp.dll"]

感谢您的帮助!

@jandrew 感谢您的评论。 我无法使用文档 (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#call-services-from-main) 1:1 中的方法,因为我正在构建 .net 核心控制台应用程序而不是 asp.net 核心应用程序。

我用 ConfigureServices 而不是 ConfigureWebHostDefaults。适合我