【问题标题】:.net Core Console application in Docker Container throws System.ObjectDisposedExceptionDocker 容器中的 .net Core 控制台应用程序抛出 System.ObjectDisposedException
【发布时间】:2020-03-18 18:01:32
【问题描述】:

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

简而言之,我有一个想要在 Docker 中运行的 .net Core 3.1 控制台应用程序。如果我在 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&lt;IConfigService&gt;(); 行正在运行。

正如我所提到的,一切都在 Visual Studio 中运行和工作,或者如果我在 CLI 中启动命令行工具。 只有在 Docker 中才会发生异常。 这是 DockerFile:

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"]

感谢您的帮助!

【问题讨论】:

标签: c# docker .net-core console-application


【解决方案1】:

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

我使用了ConfigureServices 而不是ConfigureWebHostDefaults。适合我

【讨论】:

  • 你的问题解决方案是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 2019-11-08
  • 2023-04-10
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多