| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

「.NET Core Console」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
 
(同じ利用者による、間の15版が非表示)
1行目: 1行目:
 
| [[.NET Core]] | [[ASP.NET Core]]  | [[C Sharp]] |  
 
| [[.NET Core]] | [[ASP.NET Core]]  | [[C Sharp]] |  
==.NET Core Console==
+
==.NET Core Console/Worker==
 +
==汎用HOST==
 +
*https://docs.microsoft.com/ja-jp/dotnet/core/extensions/generic-host
  
==設定とDIを組み込んだテンプレート==
 
 
===プロジェクト作成===
 
===プロジェクト作成===
 
<pre>
 
<pre>
$ dotnet new console -o docweb_bat
+
$ dotnet new worker -o docweb_bat2
 
$ dotnet new gitignore
 
$ dotnet new gitignore
 
</pre>
 
</pre>
12行目: 13行目:
 
<pre>
 
<pre>
 
dotnet add package Microsoft.Extensions.Configuration.Json --version 5.0.0
 
dotnet add package Microsoft.Extensions.Configuration.Json --version 5.0.0
 +
dotnet add package Microsoft.Extensions.Configuration.CommandLine --version 5.0.0
 
</pre>
 
</pre>
 +
====Logging====
 +
*Log4net
 +
<pre>
 +
dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore --version 5.0.3
 +
</pre>
 +
 
====DI====
 
====DI====
 
<pre>
 
<pre>
20行目: 28行目:
 
</pre>
 
</pre>
 
===実装===
 
===実装===
 +
----
 +
====Progmram.cs====
 +
<pre>
 +
using System;
 +
using System.Collections.Generic;
 +
using System.Linq;
 +
using System.Threading.Tasks;
 +
using docweb_bat2.Models;
 +
using docweb_bat2.Services;
 +
using Microsoft.Extensions.Configuration;
 +
using Microsoft.Extensions.DependencyInjection;
 +
using Microsoft.Extensions.Hosting;
 +
using Microsoft.Extensions.Logging;
 +
using Microsoft.Extensions.Options;
 +
 +
namespace docweb_bat2
 +
{
 +
    public class Program
 +
    {
 +
        public static void Main(string[] args)
 +
        {
 +
            CreateHostBuilder(args).Build().Run();
 +
        }
 +
           
 +
        public static IHostBuilder CreateHostBuilder(string[] args) =>
 +
            Host.CreateDefaultBuilder(args)
 +
                .ConfigureLogging((hostContext, builder) =>
 +
                {
 +
                    builder.ClearProviders();
 +
                    builder.AddLog4Net();
 +
                })
 +
                .ConfigureServices((hostContext, services) =>
 +
                {
 +
                    // requires using Microsoft.Extensions.Options
 +
                    services.Configure<DocumentWebDatabaseSettings>(
 +
                        hostContext.Configuration.GetSection(nameof(DocumentWebDatabaseSettings)));
 +
 +
                    services.AddSingleton<IDocumentWebDatabaseSettings>(sp =>
 +
                        sp.GetRequiredService<IOptions<DocumentWebDatabaseSettings>>().Value);
 +
 +
                    services.AddSingleton<IConfiguration>(hostContext.Configuration);
 +
                    services.AddSingleton<DocumentWebService>();
 +
 +
                    services.AddHostedService<Worker>();
 +
                })
 +
                ;
 +
    }
 +
}
 +
</pre>
 +
 +
====設定ロード先====
 +
<pre>
 +
namespace docWeb.Models
 +
{
 +
    public interface IDocumentWebDatabaseSettings
 +
    {
 +
        string DocumentWebCollectionName { get; set; }
 +
        string ConnectionString { get; set; }
 +
        string DatabaseName { get; set; }
 +
    }
 +
 +
    public class DocumentWebDatabaseSettings : IDocumentWebDatabaseSettings
 +
    {
 +
        public string DocumentWebCollectionName { get; set; }
 +
        public string ConnectionString { get; set; }
 +
        public string DatabaseName { get; set; }
 +
    }
 +
}
 +
</pre>
 +
 +
====ワーカー====
 +
<pre>
 +
using System;
 +
using System.Collections.Generic;
 +
using System.Linq;
 +
using System.Net.Http;
 +
using System.Text;
 +
using System.Threading;
 +
using System.Threading.Tasks;
 +
using docweb_bat2.Services;
 +
using Microsoft.Extensions.Configuration;
 +
using Microsoft.Extensions.Hosting;
 +
using Microsoft.Extensions.Logging;
 +
using MongoDB.Bson;
 +
using MongoDB.Driver;
 +
using Newtonsoft.Json;
 +
 +
namespace docweb_bat2
 +
{
 +
    public class Worker : BackgroundService
 +
    {
 +
        private readonly ILogger<Worker> _logger;
 +
 +
        private IConfiguration _config;
 +
        private DocumentWebService _service;
 +
 +
        static readonly HttpClient client = new HttpClient();
 +
 +
        public Worker(ILogger<Worker> logger, IConfiguration config, DocumentWebService service)
 +
        {
 +
            _logger = logger;
 +
            _config = config;
 +
            _service = service;
 +
        }
 +
 +
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 +
        {
 +
              :
 +
        }
 +
      }
 +
    }
 +
}
 +
</pre>
 +
===Hostedアプリケーションの停止をプログラムから===
 +
<pre>
 +
IHostApplicationLifetime _lifeTime;
 +
public MyClass(IHostApplicationLifetime lifeTime)
 +
{
 +
    _lifeTime = lifeTime;
 +
}
 +
</pre>
 +
*停止
 +
<pre>
 +
public void Exit()
 +
{
 +
    _lifeTime.StopApplication();
 +
}
 +
</pre>
 +
==汎用HOSTで実施したことをConsoleで==
 
<pre>
 
<pre>
 
using System;
 
using System;
38行目: 175行目:
 
             IServiceCollection services = new ServiceCollection();
 
             IServiceCollection services = new ServiceCollection();
 
              
 
              
             var configuration = GetConfiguration();
+
             var configuration = GetConfiguration(args);
 
              
 
              
            // 設定を設定管理オブジェクトに読み込む
 
 
             // require Microsoft.Extensions.Configuration.Binder
 
             // require Microsoft.Extensions.Configuration.Binder
 
             IDocumentWebDatabaseSettings dbSettings  
 
             IDocumentWebDatabaseSettings dbSettings  
46行目: 182行目:
 
                     .Get<DocumentWebDatabaseSettings>();
 
                     .Get<DocumentWebDatabaseSettings>();
  
             // DIによりオブジェクト関連を構築
+
             // DI
 +
            services.AddSingleton<IConfiguration>(configuration);
 
             services.AddSingleton<IDocumentWebDatabaseSettings>(sp => dbSettings);
 
             services.AddSingleton<IDocumentWebDatabaseSettings>(sp => dbSettings);
 
             services.AddSingleton<DocumentWebService>();
 
             services.AddSingleton<DocumentWebService>();
 +
 
             // JOBS
 
             // JOBS
 
             services.AddSingleton<GetCollection>();
 
             services.AddSingleton<GetCollection>();
  
            // 作業を行うオブジェクトをサービスから取り出し実行
 
 
             var job = services.BuildServiceProvider().GetService<GetCollection>();
 
             var job = services.BuildServiceProvider().GetService<GetCollection>();
 
             job.Run();
 
             job.Run();
 +
 
         }
 
         }
 
+
         private static IConfiguration GetConfiguration(string[] args) {
        // 設定のロード
+
              
         private static IConfiguration GetConfiguration() {
 
 
 
             // 環境変数(dotnet run)もしくは、launch.json(デバッガ起動時) にて上書きする設定を指定する
 
 
             // export DECWEB_ENV=Development
 
             // export DECWEB_ENV=Development
 
             // or launch.json configurations.env section  
 
             // or launch.json configurations.env section  
             var environmentName = Environment.GetEnvironmentVariable("DOCWEB_ENV"); // 環境変数
+
             var environmentName = Environment.GetEnvironmentVariable("DOCWEB_ENV");
 
             Console.WriteLine($"Environment:{environmentName}");
 
             Console.WriteLine($"Environment:{environmentName}");
  
69行目: 204行目:
 
                 .SetBasePath(Directory.GetCurrentDirectory())
 
                 .SetBasePath(Directory.GetCurrentDirectory())
 
                 .AddJsonFile("appsettings.json", true, true)
 
                 .AddJsonFile("appsettings.json", true, true)
                // 設定ファイルの一部に含める ex appsettings.Development.json
 
 
                 .AddJsonFile($"appsettings.{environmentName}.json", true, true)
 
                 .AddJsonFile($"appsettings.{environmentName}.json", true, true)
 +
                .AddCommandLine(args)
 
                 .Build();
 
                 .Build();
  

2021年7月4日 (日) 10:07時点における最新版

| .NET Core | ASP.NET Core | C Sharp |

.NET Core Console/Worker

汎用HOST

プロジェクト作成

$ dotnet new worker -o docweb_bat2
$ dotnet new gitignore

NuGet

Configuration

dotnet add package Microsoft.Extensions.Configuration.Json --version 5.0.0
dotnet add package Microsoft.Extensions.Configuration.CommandLine --version 5.0.0

Logging

  • Log4net
dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore --version 5.0.3

DI

dotnet add package Microsoft.Extensions.DependencyInjection --version 5.0.1
dotnet add package Microsoft.Extensions.Options --version 5.0.0
dotnet add package Microsoft.Extensions.Configuration.Binder --version 5.0.0

実装


Progmram.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using docweb_bat2.Models;
using docweb_bat2.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace docweb_bat2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
            
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging((hostContext, builder) =>
                {
                    builder.ClearProviders();
                    builder.AddLog4Net();
                })
                .ConfigureServices((hostContext, services) =>
                {
                    // requires using Microsoft.Extensions.Options
                    services.Configure<DocumentWebDatabaseSettings>(
                        hostContext.Configuration.GetSection(nameof(DocumentWebDatabaseSettings)));

                    services.AddSingleton<IDocumentWebDatabaseSettings>(sp =>
                        sp.GetRequiredService<IOptions<DocumentWebDatabaseSettings>>().Value);

                    services.AddSingleton<IConfiguration>(hostContext.Configuration);
                    services.AddSingleton<DocumentWebService>();

                    services.AddHostedService<Worker>();
                })
                ;
    }
}

設定ロード先

namespace docWeb.Models
{
    public interface IDocumentWebDatabaseSettings
    {
        string DocumentWebCollectionName { get; set; }
        string ConnectionString { get; set; }
        string DatabaseName { get; set; }
    }

    public class DocumentWebDatabaseSettings : IDocumentWebDatabaseSettings
    {
        public string DocumentWebCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }
}

ワーカー

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using docweb_bat2.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;

namespace docweb_bat2
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        private IConfiguration _config;
        private DocumentWebService _service;

        static readonly HttpClient client = new HttpClient();

        public Worker(ILogger<Worker> logger, IConfiguration config, DocumentWebService service)
        {
            _logger = logger;
            _config = config;
            _service = service;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
              :
        }
      }
    }
}

Hostedアプリケーションの停止をプログラムから

IHostApplicationLifetime _lifeTime;
public MyClass(IHostApplicationLifetime lifeTime)
{
    _lifeTime = lifeTime;
}
  • 停止
public void Exit()
{
    _lifeTime.StopApplication();
}

汎用HOSTで実施したことをConsoleで

using System;
using System.IO;
using docweb.Services;
using docWeb.Models;
using docweb_bat.Jobs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace docweb_bat
{
    public class Program
    {
        static void Main(string[] args)
        {
            IServiceCollection services = new ServiceCollection();
            
            var configuration = GetConfiguration(args);
            
            // require Microsoft.Extensions.Configuration.Binder
            IDocumentWebDatabaseSettings dbSettings 
                = configuration.GetSection(nameof(DocumentWebDatabaseSettings))
                    .Get<DocumentWebDatabaseSettings>();

            // DI
            services.AddSingleton<IConfiguration>(configuration);
            services.AddSingleton<IDocumentWebDatabaseSettings>(sp => dbSettings);
            services.AddSingleton<DocumentWebService>();

            // JOBS
            services.AddSingleton<GetCollection>();

            var job = services.BuildServiceProvider().GetService<GetCollection>();
            job.Run();

        }
        private static IConfiguration GetConfiguration(string[] args) {
            
            // export DECWEB_ENV=Development
            // or launch.json configurations.env section 
            var environmentName = Environment.GetEnvironmentVariable("DOCWEB_ENV");
            Console.WriteLine($"Environment:{environmentName}");

            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{environmentName}.json", true, true)
                .AddCommandLine(args)
                .Build();

            return configuration;
        }
    }
}