如何使用 dockerfile 将参数传递给 .NET 核心项目 [英] How to pass parameters to a .NET core project with dockerfile

查看:25
本文介绍了如何使用 dockerfile 将参数传递给 .NET 核心项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET 核心项目(使用 Visual Studio 并通过

解决方案

我也使用了可以通过docker-compse.yml设置的环境变量

公共静态类 EnvironmentHelper{公共常量字符串 EnvironmentArguments = "DOTNETCORE_ARGUMENTS";私有静态字符串 [] _arguments;公共静态字符串 [] 参数{得到{bool argumentsExist = _arguments != null &&_arguments.Any();if (!argumentsExist){IDictionary environmentVariables = Environment.GetEnvironmentVariables();if (!environmentVariables.Contains(EnvironmentArguments)){throw new Exception("环境参数不存在");}var argumentsHolder = environmentVariables[EnvironmentArguments] 作为字符串;const char argumentSeparator = ' ';_arguments = argumentsHolder?.Split(argumentSeparator);}返回_arguments;}}}

I've got a .NET Core project (using visual studio and adding the docker files via the Visual Studio Tools for Docker).

My DockerFile looks like this:

FROM microsoft/dotnet:1.0.1-core
ARG source=.
WORKDIR /app
COPY $source .
ENTRYPOINT ["dotnet", "MyApp.dll"]
CMD ["arg1", "arg2"]

My question is, how do I pass parameters into the project?

public static void Main(string[] args)
{
    // how does `args` get populated?
}

解决方案

I used environment variables which can be set by docker-compse.yml too

public static class EnvironmentHelper
{
    public const string EnvironmentArguments = "DOTNETCORE_ARGUMENTS";
    private static string[] _arguments;
    public static string[] Arguments
    {
        get
        {
            bool argumentsExist = _arguments != null && _arguments.Any();
            if (!argumentsExist)
            {
                IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                if (!environmentVariables.Contains(EnvironmentArguments))
                {
                    throw new Exception("Environment Arguments do not exist");
                }
                var argumentsHolder = environmentVariables[EnvironmentArguments] as string;
                const char argumentSeparator = ' ';
                _arguments = argumentsHolder?.Split(argumentSeparator);
            }
            return _arguments;
        }
    }
}

这篇关于如何使用 dockerfile 将参数传递给 .NET 核心项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆