「.NET Core」の版間の差分
ナビゲーションに移動
検索に移動
(同じ利用者による、間の36版が非表示) | |||
1行目: | 1行目: | ||
− | | [[C Sharp]] | [[ASP.NET Core]] | [[.NET Core Console]] | [[Xamarin]] | | + | | [[C Sharp]] | [[ASP.NET Core]] | [[.NET Core Console]] | [[Blazor]] | [[Xamarin]] | [[Ubuntu]] | |
==[[.NET Core]]== | ==[[.NET Core]]== | ||
{{amazon|B07TYN6D5G}} | {{amazon|B07TYN6D5G}} | ||
33行目: | 33行目: | ||
*https://docs.microsoft.com/ja-jp/dotnet/core/install/macos | *https://docs.microsoft.com/ja-jp/dotnet/core/install/macos | ||
*[[ASP.NET Core]]参照 | *[[ASP.NET Core]]参照 | ||
+ | |||
+ | ===[[Linux]]=== | ||
+ | *[https://docs.microsoft.com/ja-jp/dotnet/core/install/linux?WT.mc_id=dotnet-35129-website Linuxにインストール] | ||
+ | ====[[Ubuntu]]==== | ||
+ | *[https://www.typea.info/blog/index.php/2022/04/16/ubuntu_nginx_asp_net_core/ Ubuntu+Nginx+ASP.NET Core] | ||
+ | *[https://docs.microsoft.com/ja-jp/dotnet/core/install/linux-ubuntu Ubuntuにインストール] | ||
+ | *.NET アプリを開発する場合は、SDK をインストール (ランタイムが含まれます) | ||
+ | *アプリを実行する必要があるだけの場合は、ランタイムをインストール | ||
+ | * ランタイムをインストールする場合は、ASP.NET Core ランタイムをインストールすることを推奨(.NET と ASP.NET の Core ランタイムの両方が含まれているため) | ||
+ | |||
+ | =====20.04===== | ||
+ | *信頼されたキーの一覧に Microsoft パッケージ署名キーを追加し、パッケージ リポジトリを追加 | ||
+ | <pre> | ||
+ | $ wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb | ||
+ | $ sudo dpkg -i packages-microsoft-prod.deb | ||
+ | $ rm packages-microsoft-prod.deb | ||
+ | </pre> | ||
+ | |||
+ | *.NET 6.0 SDK インストール | ||
+ | <pre> | ||
+ | $ sudo apt-get update | ||
+ | $ sudo apt-get install -y apt-transport-https | ||
+ | $ sudo apt-get install -y dotnet-sdk-6.0 | ||
+ | </pre> | ||
+ | |||
+ | *.NET 6.0 Runtime インストール | ||
+ | <pre> | ||
+ | $ sudo apt-get update | ||
+ | $ sudo apt-get install -y apt-transport-https | ||
+ | $ sudo apt-get install -y aspnetcore-runtime-6.0 | ||
+ | </pre> | ||
+ | =====おかしい場合、インストールのやり直し===== | ||
+ | https://stackoverflow.com/questions/73312785/dotnet-sdk-is-installed-but-not-recognized-linux-ubuntu-popos-22-04 | ||
+ | |||
+ | Removed all .NET packages | ||
+ | sudo apt remove 'dotnet*' | ||
+ | sudo apt remove 'aspnetcore*' | ||
+ | |||
+ | Deleted PMC repository from APT, by deleting the repo .list file | ||
+ | sudo rm /etc/apt/sources.list.d/microsoft-prod.list | ||
+ | Ran sudo apt update | ||
+ | Installed .NET 6 SDK via sudo apt install dotnet-sdk-6.0 | ||
+ | |||
+ | ====Nginx==== | ||
+ | *[https://docs.microsoft.com/ja-jp/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-6.0 NginxでASP.Netをホスト] | ||
+ | *[https://www.nginx.com/resources/wiki/start/topics/tutorials/install/#official-debian-ubuntu-packages Nginxのインストール] | ||
+ | <pre> | ||
+ | $ sudo apt update | ||
+ | $ sudo apt install nginx | ||
+ | $ sudo service nginx start | ||
+ | </pre> | ||
+ | [[File:nginx_start.png | 400px]] | ||
+ | |||
+ | *構成 | ||
+ | **/etc/nginx/sites-available/default に追記 | ||
+ | **https://qiita.com/okatako/items/b04ddd9c4f5631d0cc40 | ||
+ | <pre> | ||
+ | server { | ||
+ | listen 80; | ||
+ | listen [::]:80; | ||
+ | server_name dotnet-study.local *.dotnet-study.local; | ||
+ | location / { | ||
+ | proxy_pass http://127.0.0.1:5000; | ||
+ | proxy_http_version 1.1; | ||
+ | proxy_set_header Upgrade $http_upgrade; | ||
+ | proxy_set_header Connection keep-alive; | ||
+ | proxy_set_header Host $host; | ||
+ | proxy_cache_bypass $http_upgrade; | ||
+ | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; | ||
+ | proxy_set_header X-Forwarded-Proto $scheme; | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | *[[Blazor]] Serverサービスを構成 | ||
+ | <pre> | ||
+ | $ sudo vi /etc/systemd/system/blazorsvr-app.service | ||
+ | </pre> | ||
+ | <pre> | ||
+ | [Unit] | ||
+ | Description=Example .NET Blazor Server running on Ubuntu | ||
+ | |||
+ | [Service] | ||
+ | WorkingDirectory=/home/piroto/blazorserver | ||
+ | ExecStart=/usr/bin/dotnet /home/piroto/blazorserver/blazorserver.dll | ||
+ | Restart=always | ||
+ | # Restart service after 10 seconds if the dotnet service crashes: | ||
+ | RestartSec=10 | ||
+ | KillSignal=SIGINT | ||
+ | SyslogIdentifier=dotnet-example | ||
+ | User=www-data | ||
+ | Environment=ASPNETCORE_ENVIRONMENT=Production | ||
+ | Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false | ||
+ | |||
+ | [Install] | ||
+ | WantedBy=multi-user.target | ||
+ | </pre> | ||
+ | *サービス開始 | ||
+ | <pre> | ||
+ | $ sudo systemctl start blazorsvr-app.service | ||
+ | </pre> | ||
+ | *サービス確認 | ||
+ | <pre> | ||
+ | $ sudo systemctl status blazorsvr-app.service | ||
+ | ● blazorsvr-app.service - Example .NET Blazor Server running on Ubuntu | ||
+ | Loaded: loaded (/etc/systemd/system/blazorsvr-app.service; disabled; vendor preset: enabled) | ||
+ | Active: active (running) since Fri 2022-04-15 21:43:22 JST; 5s ago | ||
+ | Main PID: 15301 (dotnet) | ||
+ | Tasks: 18 (limit: 2338) | ||
+ | Memory: 23.5M | ||
+ | CGroup: /system.slice/blazorsvr-app.service | ||
+ | └─15301 /usr/bin/dotnet /home/piroto/blazorserver/blazorserver.dll | ||
+ | |||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: warn: Microsoft.AspNetCore.DataProtection.KeyManagem> | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: No XML encryptor configured. Key {00c25811-cc1> | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[14] | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Now listening on: http://localhost:5000 | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[0] | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Application started. Press Ctrl+C to shut down. | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[0] | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Hosting environment: Production | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[0] | ||
+ | Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Content root path: /home/piroto/blazorserver/ | ||
+ | </pre> | ||
+ | [[File:blazor_on_ubuntu.png | 400px]] | ||
===アンインストールツール=== | ===アンインストールツール=== | ||
90行目: | 214行目: | ||
---- | ---- | ||
*https://docs.microsoft.com/ja-jp/dotnet/core/tools/dotnet-new?tabs=netcore21 | *https://docs.microsoft.com/ja-jp/dotnet/core/tools/dotnet-new?tabs=netcore21 | ||
− | + | ||
+ | <pre> | ||
+ | $ dotnet new web | ||
+ | </pre> | ||
+ | |||
+ | *一覧表示 | ||
+ | <pre> | ||
+ | $ dotnet new --list | ||
+ | これらのテンプレートは、入力: と一致しました | ||
+ | |||
+ | テンプレート名 短い名前 言語 タグ | ||
+ | --------------------------------- -------------- ---------- -------------------------- | ||
+ | ASP.NET Core Empty web [C#],F# Web/Empty | ||
+ | ASP.NET Core gRPC Service grpc [C#] Web/gRPC | ||
+ | ASP.NET Core Web API webapi [C#],F# Web/WebAPI | ||
+ | ASP.NET Core Web App webapp,razor [C#] Web/MVC/Razor Pages | ||
+ | ASP.NET Core Web App (Model-Vi... mvc [C#],F# Web/MVC | ||
+ | ASP.NET Core with Angular angular [C#] Web/MVC/SPA | ||
+ | ASP.NET Core with React.js react [C#] Web/MVC/SPA | ||
+ | Blazor Server App blazorserver [C#] Web/Blazor | ||
+ | Blazor WebAssembly App blazorwasm [C#] Web/Blazor/WebAssembly/PWA | ||
+ | dotnet gitignore ファイル gitignore Config | ||
+ | dotnet ローカル ツール マニフ... tool-manifest Config | ||
+ | EditorConfig ファイル editorconfig Config | ||
+ | global.json ファイル globaljson Config | ||
+ | MSTest Test Project mstest [C#],F#,VB Test/MSTest | ||
+ | MVC ViewImports viewimports [C#] Web/ASP.NET | ||
+ | MVC ViewStart viewstart [C#] Web/ASP.NET | ||
+ | NuGet Config nugetconfig Config | ||
+ | NUnit 3 Test Item nunit-test [C#],F#,VB Test/NUnit | ||
+ | NUnit 3 Test Project nunit [C#],F#,VB Test/NUnit | ||
+ | Protocol Buffer File proto Web/gRPC | ||
+ | Razor Class Library razorclasslib [C#] Web/Razor/Library | ||
+ | Razor Component razorcomponent [C#] Web/ASP.NET | ||
+ | Razor Page page [C#] Web/ASP.NET | ||
+ | Web 構成 webconfig Config | ||
+ | Worker Service worker [C#],F# Common/Worker/Web | ||
+ | xUnit Test Project xunit [C#],F#,VB Test/xUnit | ||
+ | クラス ライブラリ classlib [C#],F#,VB Common/Library | ||
+ | コンソール アプリ console [C#],F#,VB Common/Console | ||
+ | ソリューション ファイル sln Solution | ||
+ | </pre> | ||
====ソリューション==== | ====ソリューション==== | ||
---- | ---- | ||
*カレントディレクトリにソリューションファイルを作成 | *カレントディレクトリにソリューションファイルを作成 | ||
+ | *"."で親フォルダ名と同一、名前を指定すればその名前 | ||
<pre> | <pre> | ||
$ dotnet new sln -o . | $ dotnet new sln -o . | ||
223行目: | 389行目: | ||
==Console== | ==Console== | ||
+ | ===コマンドライン オプションの解析=== | ||
+ | ---- | ||
+ | * https://docs.microsoft.com/ja-jp/archive/msdn-magazine/2019/march/net-parse-the-command-line-with-system-commandline | ||
+ | * https://blog.yucchiy.com/2021/03/intro-system-commandline/ | ||
+ | * https://qiita.com/TsuyoshiUshio@github/items/02902f4f46f0aa37e4b1 | ||
+ | * System.ConmmandLineは.NETでコンソールアプリケーション(CLI)を作るための.NET公式のライブラリ | ||
+ | |||
+ | <pre> | ||
+ | dotnet add package System.CommandLine --version 2.0.0-beta3.22111.2 | ||
+ | </pre> | ||
+ | |||
+ | <pre> | ||
+ | using System; | ||
+ | using System.CommandLine; | ||
+ | using System.CommandLine.Invocation; | ||
+ | using System.IO; | ||
+ | using System.Reflection; | ||
+ | |||
+ | public class Program | ||
+ | { | ||
+ | static int Main(string[] args) | ||
+ | { | ||
+ | var converterOption = new Argument<string>("converter", "Converter Name"); | ||
+ | var infoOption = new Option<bool>(new string[] { "-i", "--info" }, "information"); | ||
+ | var rootCommand = new RootCommand { converterOption, infoOption }; | ||
+ | rootCommand.Description = "Convert"; | ||
+ | |||
+ | rootCommand.SetHandler((string converter, bool info) => | ||
+ | { | ||
+ | Console.WriteLine($"{converter} {info}"); | ||
+ | }, converterOption, infoOption); | ||
+ | |||
+ | return rootCommand.Invoke(args); | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | |||
+ | <pre> | ||
+ | |||
+ | Description: | ||
+ | Convert | ||
+ | |||
+ | hogehoge <converter> [options] | ||
+ | |||
+ | Arguments: | ||
+ | <converter> Converter Name | ||
+ | |||
+ | Options: | ||
+ | -i, --info information | ||
+ | --version Show version information | ||
+ | -?, -h, --help Show help and usage information | ||
+ | |||
+ | > dotnet run "conv" | ||
+ | conv False | ||
+ | </pre> | ||
+ | |||
===設定ファイル=== | ===設定ファイル=== | ||
<pre> | <pre> |
2023年3月11日 (土) 00:15時点における最新版
| C Sharp | ASP.NET Core | .NET Core Console | Blazor | Xamarin | Ubuntu |
.NET Core
.NET Core
- 最新の .NET 実装です。オープン ソースで、複数の OS 向けに利用できます。
- .NET Core により、クロスプラットフォーム コンソール アプリケーション、ASP.NET Core Web アプリケーション、およびクラウド サービスをビルドできます。
.NET Standard
- すべての .NET 実装が実装する必要のある基本 API のセットです。
- この API を基本クラス ライブラリ (BCL) と呼びます。
- .NET Standard をターゲットにすることで、どの .NET 実装やどの OS で実行されても、すべての .NET アプリケーションが共有できるライブラリをビルドできます。
.NET API ブラウザ
.NET ソースブラウザ
インストール
ダウンロード
Mac
- https://dotnet.microsoft.com/download/dotnet/3.1
- https://docs.microsoft.com/ja-jp/dotnet/core/install/macos
- ASP.NET Core参照
Linux
Ubuntu
- Ubuntu+Nginx+ASP.NET Core
- Ubuntuにインストール
- .NET アプリを開発する場合は、SDK をインストール (ランタイムが含まれます)
- アプリを実行する必要があるだけの場合は、ランタイムをインストール
- ランタイムをインストールする場合は、ASP.NET Core ランタイムをインストールすることを推奨(.NET と ASP.NET の Core ランタイムの両方が含まれているため)
20.04
- 信頼されたキーの一覧に Microsoft パッケージ署名キーを追加し、パッケージ リポジトリを追加
- $ wget https://packages.microsoft.com/config/ubuntu/20.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
- $ sudo dpkg -i packages-microsoft-prod.deb
- $ rm packages-microsoft-prod.deb
- .NET 6.0 SDK インストール
- $ sudo apt-get update
- $ sudo apt-get install -y apt-transport-https
- $ sudo apt-get install -y dotnet-sdk-6.0
- .NET 6.0 Runtime インストール
- $ sudo apt-get update
- $ sudo apt-get install -y apt-transport-https
- $ sudo apt-get install -y aspnetcore-runtime-6.0
おかしい場合、インストールのやり直し
Removed all .NET packages
- sudo apt remove 'dotnet*'
- sudo apt remove 'aspnetcore*'
Deleted PMC repository from APT, by deleting the repo .list file
- sudo rm /etc/apt/sources.list.d/microsoft-prod.list
Ran sudo apt update
- Installed .NET 6 SDK via sudo apt install dotnet-sdk-6.0
Nginx
- $ sudo apt update
- $ sudo apt install nginx
- $ sudo service nginx start
- 構成
- /etc/nginx/sites-available/default に追記
- https://qiita.com/okatako/items/b04ddd9c4f5631d0cc40
- server {
- listen 80;
- listen [::]:80;
- server_name dotnet-study.local *.dotnet-study.local;
- location / {
- proxy_pass http://127.0.0.1:5000;
- proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection keep-alive;
- proxy_set_header Host $host;
- proxy_cache_bypass $http_upgrade;
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
- }
- }
- Blazor Serverサービスを構成
- $ sudo vi /etc/systemd/system/blazorsvr-app.service
- [Unit]
- Description=Example .NET Blazor Server running on Ubuntu
- [Service]
- WorkingDirectory=/home/piroto/blazorserver
- ExecStart=/usr/bin/dotnet /home/piroto/blazorserver/blazorserver.dll
- Restart=always
- # Restart service after 10 seconds if the dotnet service crashes:
- RestartSec=10
- KillSignal=SIGINT
- SyslogIdentifier=dotnet-example
- User=www-data
- Environment=ASPNETCORE_ENVIRONMENT=Production
- Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
- [Install]
- WantedBy=multi-user.target
- サービス開始
- $ sudo systemctl start blazorsvr-app.service
- サービス確認
- $ sudo systemctl status blazorsvr-app.service
- ● blazorsvr-app.service - Example .NET Blazor Server running on Ubuntu
- Loaded: loaded (/etc/systemd/system/blazorsvr-app.service; disabled; vendor preset: enabled)
- Active: active (running) since Fri 2022-04-15 21:43:22 JST; 5s ago
- Main PID: 15301 (dotnet)
- Tasks: 18 (limit: 2338)
- Memory: 23.5M
- CGroup: /system.slice/blazorsvr-app.service
- └─15301 /usr/bin/dotnet /home/piroto/blazorserver/blazorserver.dll
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: warn: Microsoft.AspNetCore.DataProtection.KeyManagem>
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: No XML encryptor configured. Key {00c25811-cc1>
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[14]
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Now listening on: http://localhost:5000
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[0]
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Application started. Press Ctrl+C to shut down.
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[0]
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Hosting environment: Production
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: info: Microsoft.Hosting.Lifetime[0]
- Apr 15 21:43:23 dotnet-study dotnet-example[15301]: Content root path: /home/piroto/blazorserver/
アンインストールツール
CLIコマンド
SDKコマンド
コマンド | 内容 |
---|---|
dotnet --info | .NET Core 情報の表示 |
パッケージの追加
- dotnet add package Microsoft.Extensions.Configuration.Binder --version 5.0.0
- dotnet add package Microsoft.Extensions.Configuration.CommandLine --version 5.0.0
- dotnet add package Microsoft.Extensions.Configuration.Json --version 5.0.0
- dotnet add package Microsoft.Extensions.DependencyInjection --version 5.0.1
- dotnet add package Microsoft.Extensions.Hosting --version 5.0.0
- dotnet add package Microsoft.Extensions.Options --version 5.0.0
- dotnet add package MongoDB.Driver --version 2.12.4
- dotnet add package Newtonsoft.Json.Bson --version 1.0.2
- dotnet add package Newtonsoft.Json --version 13.0.1
- dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore --version 5.0.3
Windows Proxy設定について
- 一時的に環境変数にプロキシを設定して対応
- set HTTP_PROXY=http:(ユーザーID):(パスワード)@(プロキシ):(ポート番号)
- set HTTPS_PROXY=http:(ユーザーID):(パスワード)@(プロキシ):(ポート番号)
> netsh winhttp show proxy > netsh winhttp import proxy source=ie
.gitignoreの作成
- $ dotnet new gitignore
プロジェクトレンプレート
dotnet new
- $ dotnet new web
- 一覧表示
- $ dotnet new --list
- これらのテンプレートは、入力: と一致しました
- テンプレート名 短い名前 言語 タグ
- --------------------------------- -------------- ---------- --------------------------
- ASP.NET Core Empty web [C#],F# Web/Empty
- ASP.NET Core gRPC Service grpc [C#] Web/gRPC
- ASP.NET Core Web API webapi [C#],F# Web/WebAPI
- ASP.NET Core Web App webapp,razor [C#] Web/MVC/Razor Pages
- ASP.NET Core Web App (Model-Vi... mvc [C#],F# Web/MVC
- ASP.NET Core with Angular angular [C#] Web/MVC/SPA
- ASP.NET Core with React.js react [C#] Web/MVC/SPA
- Blazor Server App blazorserver [C#] Web/Blazor
- Blazor WebAssembly App blazorwasm [C#] Web/Blazor/WebAssembly/PWA
- dotnet gitignore ファイル gitignore Config
- dotnet ローカル ツール マニフ... tool-manifest Config
- EditorConfig ファイル editorconfig Config
- global.json ファイル globaljson Config
- MSTest Test Project mstest [C#],F#,VB Test/MSTest
- MVC ViewImports viewimports [C#] Web/ASP.NET
- MVC ViewStart viewstart [C#] Web/ASP.NET
- NuGet Config nugetconfig Config
- NUnit 3 Test Item nunit-test [C#],F#,VB Test/NUnit
- NUnit 3 Test Project nunit [C#],F#,VB Test/NUnit
- Protocol Buffer File proto Web/gRPC
- Razor Class Library razorclasslib [C#] Web/Razor/Library
- Razor Component razorcomponent [C#] Web/ASP.NET
- Razor Page page [C#] Web/ASP.NET
- Web 構成 webconfig Config
- Worker Service worker [C#],F# Common/Worker/Web
- xUnit Test Project xunit [C#],F#,VB Test/xUnit
- クラス ライブラリ classlib [C#],F#,VB Common/Library
- コンソール アプリ console [C#],F#,VB Common/Console
- ソリューション ファイル sln Solution
ソリューション
- カレントディレクトリにソリューションファイルを作成
- "."で親フォルダ名と同一、名前を指定すればその名前
- $ dotnet new sln -o .
- カレントディレクトリのソリューションにプロジェクトを追加
- $ dotnet sln add {プロジェクトファイルパス}
- ビルド
- $ dotnet clean
- $ dotnet build
NET での依存関係の挿入
サービスの有効期間
意味 | 名称 | 内容 |
---|---|---|
一時的 | AddTransient | 有効期間が一時的なサービスは、サービス コンテナーから要求されるたびに作成されます。 この有効期間は、軽量でステートレスのサービスに最適です |
スコープ | AddScoped | Web アプリケーションの場合、スコープ付き有効期間は、クライアント要求 (接続) ごとにサービスが 1 回作成されることを示します |
シングルトン | AddSingleton | シングルトン有効期間サービスが作成されるのは、次のいずれかの場合です。
|
サービス登録メソッド
メソッド | 例 | 自動object破棄 | 複数実装 | 引数を渡す |
---|---|---|---|---|
Add{LIFETIME}<{SERVICE}, {IMPLEMENTATION}>() | services.AddSingleton<IMyDep, MyDep>(); | Y | Y | N |
Add{LIFETIME}<{SERVICE}>(sp => new {IMPLEMENTATION}) | services.AddSingleton<IMyDep>(sp => new MyDep());
services.AddSingleton<IMyDep>(sp => new MyDep(99)); |
Y | Y | Y |
Add{LIFETIME}<{IMPLEMENTATION}>() | services.AddSingleton<MyDep>(); | Y | N | N |
AddSingleton<{SERVICE}>(new {IMPLEMENTATION}) | services.AddSingleton<IMyDep>(new MyDep());
services.AddSingleton<IMyDep>(new MyDep(99)); |
N | Y | Y |
AddSingleton(new {IMPLEMENTATION}) | services.AddSingleton(new MyDep());
services.AddSingleton(new MyDep(99)); |
N | N | Y |
Cannot consume scoped service from singleton
- 既定では、開発環境で、より長い有効期間を持つ別のサービスからサービスを解決すると、例外がスローされます。
- スコープの検証
- シングルトンからスコープ付きサービスを解決 しない でください。また、たとえば一時的なサービスにより、間接的に解決しないようにご注意ください
コンソールアプリケーションでDIからサービスを取得
- return Host.CreateDefaultBuilder (args)
- .ConfigureServices ((hostContext, services) => {
- services.AddSingleton<ServiceProvider>(services.BuildServiceProvider());
- });
- ServiceProvider をコンストラクタインジェクション
- 利用時
- _serviceProvider.GetService<IHoge>()
exe を出力
デプロイ方法の名称 | 略称 | 実行方法 |
---|---|---|
Framework-dependent deployments | FDD | コマンドで dotnet hoge.dll として実行する |
Self-contained deployments | SCD | 実行ファイルを直接実行する |
日本語コーデック
- NuGet で System.Text.Encoding.CodePages を追加
- 初期化時に 以下を実行
Console
コマンドライン オプションの解析
- https://docs.microsoft.com/ja-jp/archive/msdn-magazine/2019/march/net-parse-the-command-line-with-system-commandline
- https://blog.yucchiy.com/2021/03/intro-system-commandline/
- https://qiita.com/TsuyoshiUshio@github/items/02902f4f46f0aa37e4b1
- System.ConmmandLineは.NETでコンソールアプリケーション(CLI)を作るための.NET公式のライブラリ
- dotnet add package System.CommandLine --version 2.0.0-beta3.22111.2
- using System;
- using System.CommandLine;
- using System.CommandLine.Invocation;
- using System.IO;
- using System.Reflection;
- public class Program
- {
- static int Main(string[] args)
- {
- var converterOption = new Argument<string>("converter", "Converter Name");
- var infoOption = new Option<bool>(new string[] { "-i", "--info" }, "information");
- var rootCommand = new RootCommand { converterOption, infoOption };
- rootCommand.Description = "Convert";
- rootCommand.SetHandler((string converter, bool info) =>
- {
- Console.WriteLine($"{converter} {info}");
- }, converterOption, infoOption);
- return rootCommand.Invoke(args);
- }
- }
- Description:
- Convert
- hogehoge <converter> [options]
- Arguments:
- <converter> Converter Name
- Options:
- -i, --info information
- --version Show version information
- -?, -h, --help Show help and usage information
- > dotnet run "conv"
- conv False
設定ファイル
- dotnet add package Microsoft.Extensions.Configuration.Json --version 5.0.0
- using System;
- using System.IO;
- using Microsoft.Extensions.Configuration;
- namespace docweb_bat
- {
- public class Program
- {
- static void Main(string[] args)
- {
- // export DECWEB_ENV=Development
- 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)
- .Build();
- IConfigurationSection section = configuration.GetSection("DocumentWebDatabaseSettings");
- string str = section["DocumentWebCollectionName"];
- Console.WriteLine(str);
- }
- }
- }
© 2006 矢木浩人