LoginSignup
11
15

More than 3 years have passed since last update.

ConsoleAppFrameworkを試してみる

Last updated at Posted at 2019-02-21

MagicOnion で個人的に気になってる Cysharp さんからバッチ用のフレームワークがリリースさたみたいです。

とりあえず、ドキュメント読みながら hello world 的なものを動かしたいと思います。

環境

  • os: macOSX Mojave
  • macのdotnet: version 2.2.101

と同じようにmacで開発していきます。

実装

とりあえずReadMeにある一番シンプルなコードを動かしてみます。

まず、dotnetコマンドを使って新規プロジェクトを作成します。

$ dotnet new console

試しにちゃんと動くかdotnet runで確認してみます。
問題がなければ「Hello World!」と表示されます。

$ dotnet run
Hello World!

次にパッケージを導入します。

の.NET CLIにあるものをコピペします。

$ dotnet add package ConsoleAppFramework --version 2.0.0

これ以外にも複数のパッケージを使うので導入します。

$ dotnet add package Microsoft.Extensions.Logging
$ dotnet add package Microsoft.Extensions.Hosting

また、今回のコードではasyncを使うので、C#のバージョンを7.1以上にする必要があります。
.Net CoreプロジェクトでC#のバージョンを変更する方法
こちらの記事を参考に.csprojファイルに<LangVersion>7.3</LangVersion>を追加します。
7.3にしたのはsandboxにあるサンプルの.csprojで7.3が指定されていたからです。

最後にProgram.csを編集します。
これはReadMeに書いてあるまんまをコピペします。

Program.cs
using ConsoleAppFramework;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading.Tasks;

// Entrypoint, create from the .NET Core Console App.
class Program : ConsoleAppBase // inherit ConsoleAppBase
{
    static async Task Main(string[] args)
    {
        // target T as ConsoleAppBase.
        await Host.CreateDefaultBuilder().RunConsoleAppFrameworkAsync<Program>(args);
    }

    // allows void/Task return type, parameter is automatically binded from string[] args.
    public void Run(string name, int repeat = 3)
    {
        for (int i = 0; i < repeat; i++)
        {
            Console.WriteLine($"Hello My ConsoleApp from {name}");
        }
    }
}

あとはdotnet runで実行します。

$ dotnet run -name "orange634nty" -repeat 5
Hello My Batch from orange634nty
Hello My Batch from orange634nty
Hello My Batch from orange634nty
Hello My Batch from orange634nty
Hello My Batch from orange634nty

ついでにpublishも試してみました。

$ dotnet publish --runtime osx.10.13-x64
# bin/Debug/netcoreapp2.2/osx.10.13-x64/publish/ にビルドされたものが出力される
$ ./bin/Debug/netcoreapp2.2/osx.10.13-x64/publish/console-app-framework-test -name "orange634nty" -repeat 5
Hello My Batch from orange634nty
Hello My Batch from orange634nty
Hello My Batch from orange634nty
Hello My Batch from orange634nty
Hello My Batch from orange634nty

こちらも問題なく動きます。

完成品はこちらのリポジトリに上げておきます。

おまけ

versionを上げる方法

csproj ファイルの ConsoleAppFrameworkVersion を変更します。

<PackageReference Include="ConsoleAppFramework" Version="2.0.0" />

dotnet restore でパッケージの依存関係を復元します。
問題なく復元されたら、OKです。

感想

まだ動かしただけなので、わかっていませんがかなり簡単に導入できました。
引数をパースしたり、helpを作ったり意外とやろうとなると面倒なので、非常にありがたいですね!

11
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
15