├── .gitignore ├── LICENSE ├── README.md └── src ├── ActivitySourceLab ├── ActivitySourceLab.csproj └── Program.cs ├── AutoActivateLab ├── AutoActivateLab.csproj └── Program.cs ├── CLK.NetCoreLab.sln ├── ConfigurationLab ├── ConfigurationLab.csproj ├── FileSetting.json ├── Program.cs └── Utilities │ └── ConfigurationExtensions.cs ├── DiagnosticSourceLab ├── DiagnosticSourceLab.csproj └── Program.cs ├── HostedServiceLab ├── HostedServiceLab.csproj └── Program.cs ├── LoggerLab.Log4net ├── LoggerLab.Log4net.csproj ├── Program.cs ├── Utilities │ ├── ConfigureExtensions.cs │ ├── Log4netLogger.cs │ └── Log4netProvider.cs ├── appsettings.json └── log4net.config ├── LoggerLab.NLog ├── LoggerLab.NLog.csproj ├── Program.cs ├── appsettings.json └── nlog.config ├── LoggerLab.Serilog ├── LoggerLab.Serilog.csproj ├── Program.cs ├── appsettings.json └── serilog.json ├── LoggerLab ├── LoggerLab.csproj ├── Program.cs └── appsettings.json ├── NamedServiceLab ├── NamedServiceLab.csproj └── Program.cs ├── ObserverLab ├── ObserverLab.csproj ├── Program.cs └── Utilities │ └── Observable.cs ├── OpenTelemetryLab ├── OpenTelemetryLab.csproj └── Program.cs ├── OptionsLab ├── OptionsLab.csproj ├── Program.cs └── appsettings.json ├── ProgramServiceLab ├── Program.cs ├── ProgramServiceLab.csproj └── Utilities │ ├── Extensions │ ├── ServiceCollectionExtensions.cs │ └── TypeExtensions.cs │ ├── ProgramService.cs │ └── ServiceActivator.cs ├── QuartzLab ├── Program.cs └── QuartzLab.csproj ├── RegisterModuleLab ├── Program.cs └── RegisterModuleLab.csproj ├── RemoveServiceLab ├── Program.cs ├── RemoveServiceLab.csproj └── Utilities │ └── Extensions │ └── ServiceCollectionExtensions.cs ├── TemplateLab ├── Program.cs └── TemplateLab.csproj ├── TraceContextLab.SubService ├── Program.cs └── TraceContextLab.SubService.csproj ├── TraceContextLab ├── Program.cs └── TraceContextLab.csproj └── WithParameterLab ├── Program.cs └── WithParameterLab.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Clark 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CLK.NetCoreLab 2 | 3 | 4 | ## [.NET Core] Logger 程式範例 (NLog/Log4net/Serilog) 5 | 6 | .NET Core裡內建了ILogger提供Log寫入功能。本篇範例程式展示如何使用內建的ILogger進行Log寫入,並展示如何在.NET Core裡掛載NLog/Log4net/Serilog做為Log輸出實作。 7 | 8 | 範例原碼:https://github.com/Clark159/CLK.NetCoreLab 9 | 10 | 範例專案: 11 | 12 | 1. LoggerLab:使用內建ILogger進行Log寫入,於Console內檢視Log紀錄。 13 | 14 | 2. LoggerLab.NLog:掛載NLog做為Log輸出實作,於bin\Debug\net5.0\log資料夾內檢視Log紀錄檔案。 15 | 16 | 3. LoggerLab.Log4net:掛載Log4net做為Log輸出實作,於bin\Debug\net5.0\log資料夾內檢視Log紀錄檔案。 17 | 18 | 4. LoggerLab.Serilog:掛載Serilog做為Log輸出實作,於bin\Debug\net5.0\log資料夾內檢視Log紀錄檔案。 19 | 20 | 21 | 22 | ## [.NET Core] Quartz.Net 程式範例 23 | 24 | .NET Core裡可以使用Quartz.Net進行工作排程。本篇範例程式展示如何使用內建DI及外掛的Autofac進行排程作業掛載,也展示如何使用Cron expression設定每五秒一次的執行時間。除範例程式外,技術細節也推薦下列兩篇參考資料輔助學習。 25 | 26 | 範例原碼:https://github.com/Clark159/CLK.NetCoreLab 27 | 28 | 範例專案:QuartzLab 29 | 30 | 參考資料: 31 | 32 | 1. 建立Quartz.Net基礎知識及如何在.NET Core專案內掛載排程。 [在 ASP.NET Core和Worker Service中使用Quartz.Net](https://codingnote.cc/zh-tw/p/292319/) 33 | 34 | 2. 了解Cron expression規則,以滿足各種排程執行時間需求,例如每月15號執行、每個星期三早上5點執行。 [Cron expression - 蚂蚁集团金融科技](https://tech.antfin.com/docs/10/64769) 35 | 36 | 37 | ## [.NET Core] IOptions 程式範例 38 | 39 | 在.NET Core中可以套用內建的Options Pattern,來進行強型別參數的設定+注入。除範例程式外,也推薦兩篇參考資料引導學習。 40 | 41 | 範例原碼:https://github.com/Clark159/CLK.NetCoreLab 42 | 43 | 範例專案:OptionsLab 44 | 45 | 參考資料: 46 | 47 | 1. 先從使用場景切入,了解Options Pattern的用途。 [【5min+】更好的选项实践。.Net Core中的IOptions](https://www.cnblogs.com/uoyo/p/12583149.html)。 48 | 49 | 2. 再從原始碼切入,剖析Options Pattern的原理。 [ASP.NET Core 2.1 源码学习之 Options:Configure]( https://www.cnblogs.com/RainingNight/p/strongly-typed-options-configure-in-asp-net-core.html)。 50 | 51 | 52 | ## [.NET Core] AutoActivate 程式範例 53 | 54 | .NET Core裡的Dependency Injection怎麼啟動沒有被注入的Class?我自己的做法,是選用Autofac的AutoActivate功能來完成這個需求。在Autofac裡註冊Class的時候,可以透過宣告AutoActivate,讓Autofac容器啟動的時候生成Class,並且納入容器管理。 55 | 56 | 範例原碼:https://github.com/Clark159/CLK.NetCoreLab 57 | 58 | 範例專案:AutoActivateLab 59 | 60 | 參考資料:[Autofac官網 - 自动激活组件](https://autofaccn.readthedocs.io/zh/latest/lifetime/startup.html?highlight=AutoActivate#id3) 61 | 62 | 63 | ## [.NET Core] OpenTelemetry 程式範例 64 | 65 | 在分散式微服務環境中,可以使用OpenTelemetry來進行分散式的鏈路追蹤。提供範例程式,給有興趣的朋友依序學習。 66 | 67 | 範例原碼:https://github.com/Clark159/CLK.NetCoreLab 68 | 69 | 範例專案: 70 | 71 | 1. ObserverLab: .NET Core中提供IObservable做為觀察者模式樣板。.NET Core內建的DiagnosticSource以IObservable為核心發佈埋點訊息。 72 | 73 | 2. DiagnosticSourceLab: .NET Core使用內建的DiagnosticSource提供逐條的埋點訊息。 74 | 75 | 3. ActivitySourceLab: .NET Core使用內建的ActivitySource提供使用ParentId串聯起來的樹狀埋點訊息。 76 | 77 | 4. OpenTelemetryLab: 開源的OpenTelemetry套件,提供將埋點訊息收集、彙整、導出至APM的功能。(以Uber Jaeger為範例) 78 | 79 | 5. TraceContextLab: OpenTelemetry套件搭配W3C Trace Context進行分散式導出至APM的功能。(以Uber Jaeger為範例) 80 | 81 | 後記:這些範例盡量以純粹的.NET Core進行說明。 82 | 83 | 84 | ## [.NET Core] Remove Console Log 程式範例 85 | 86 | .NET Core預設配置ConsoleLoggerProvider將Log資料輸出到Console畫面,當Log多的時候,會造成Console畫面被洗版的問題。範例程式,展示如何移除預設配置的ConsoleLoggerProvider,給有興趣的朋友參考。 87 | 88 | 範例原碼:https://github.com/Clark159/CLK.NetCoreLab 89 | 90 | 範例專案:RemoveServiceLab 91 | 92 | -------------------------------------------------------------------------------- /src/ActivitySourceLab/ActivitySourceLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/ActivitySourceLab/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | 5 | namespace ActivitySourceLab 6 | { 7 | public class Program 8 | { 9 | // Fields 10 | private static ActivitySource _activitySource = new ActivitySource("CLK.ActivitySourceLab.MainModule"); 11 | 12 | 13 | // Methods 14 | public static void Main(string[] args) 15 | { 16 | // Subscribe 17 | ActivitySource.AddActivityListener(new ActivitySourceSubscriber("CLK.ActivitySourceLab.MainModule").ActivityListener); 18 | 19 | // Diagnostic 20 | { 21 | // Pay 22 | using (var payActivity = _activitySource.StartActivity("Pay", ActivityKind.Internal)) 23 | { 24 | // Pay.SetTag 25 | payActivity?.SetTag("User", "Clark"); 26 | 27 | // Print 28 | using (var printActivity = _activitySource.StartActivity("Print", ActivityKind.Internal)) 29 | { 30 | // Print.SetTag 31 | printActivity?.SetTag("User", "Jane"); 32 | } 33 | } 34 | } 35 | } 36 | 37 | 38 | // Class 39 | public class ActivitySourceSubscriber 40 | { 41 | // Fields 42 | private readonly string _activitySourceName = null; 43 | 44 | private readonly ActivityExporter _activityExporter = new ActivityExporter(); 45 | 46 | 47 | // Constructors 48 | public ActivitySourceSubscriber(string activitySourceName) 49 | { 50 | #region Contracts 51 | 52 | if (string.IsNullOrEmpty(activitySourceName) == true) throw new ArgumentException(nameof(activitySourceName)); 53 | 54 | #endregion 55 | 56 | // Default 57 | _activitySourceName = activitySourceName; 58 | 59 | // ActivityListener 60 | this.ActivityListener = new ActivityListener(); 61 | this.ActivityListener.ShouldListenTo = this.ShouldListenTo; 62 | this.ActivityListener.Sample = this.Sample; 63 | this.ActivityListener.SampleUsingParentId = this.SampleUsingParentId; 64 | this.ActivityListener.ActivityStarted = _activityExporter.ActivityStarted; 65 | this.ActivityListener.ActivityStopped = _activityExporter.ActivityStopped; 66 | } 67 | 68 | 69 | // Properties 70 | public ActivityListener ActivityListener { get; private set; } 71 | 72 | 73 | // Methods 74 | public bool ShouldListenTo(ActivitySource activitySource) 75 | { 76 | #region Contracts 77 | 78 | if (activitySource == null) throw new ArgumentException(nameof(activitySource)); 79 | 80 | #endregion 81 | 82 | // Return 83 | return activitySource.Name == _activitySourceName; 84 | } 85 | 86 | public ActivitySamplingResult Sample(ref ActivityCreationOptions options) 87 | { 88 | // Return 89 | return ActivitySamplingResult.AllData; 90 | } 91 | 92 | public ActivitySamplingResult SampleUsingParentId(ref ActivityCreationOptions options) 93 | { 94 | // Return 95 | return ActivitySamplingResult.AllData; 96 | } 97 | } 98 | 99 | public class ActivityExporter 100 | { 101 | // Methods 102 | public void ActivityStarted(Activity activity) 103 | { 104 | #region Contracts 105 | 106 | if (activity == null) throw new ArgumentException(nameof(activity)); 107 | 108 | #endregion 109 | 110 | // Nothing 111 | 112 | } 113 | 114 | public void ActivityStopped(Activity activity) 115 | { 116 | #region Contracts 117 | 118 | if (activity == null) throw new ArgumentException(nameof(activity)); 119 | 120 | #endregion 121 | 122 | // Display 123 | Console.WriteLine($"Activity.Id: {activity.Id}"); 124 | Console.WriteLine($"Activity.ParentId: {activity.ParentId}"); 125 | Console.WriteLine($"Activity.TraceId: {activity.TraceId}"); 126 | Console.WriteLine($"Activity.DisplayName: {activity.DisplayName}"); 127 | Console.WriteLine($"Activity.Kind: {activity.Kind}"); 128 | Console.WriteLine($"Activity.StartTime: {activity.StartTimeUtc}"); 129 | Console.WriteLine($"Activity.Duration: {activity.Duration}"); 130 | Console.WriteLine($"Activity.TagObjects:"); 131 | foreach (var tag in activity.TagObjects) 132 | { 133 | Console.WriteLine($" {tag.Key}: {tag.Value}"); 134 | } 135 | Console.WriteLine(); 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/AutoActivateLab/AutoActivateLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/AutoActivateLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using System; 7 | using System.Reflection; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace AutoActivateLab 12 | { 13 | public class Program 14 | { 15 | // Methods 16 | public static void Main(string[] args) 17 | { 18 | CreateHostBuilder(args).Build().Run(); 19 | } 20 | 21 | public static IHostBuilder CreateHostBuilder(string[] args)=> 22 | Host.CreateDefaultBuilder(args) 23 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 24 | .ConfigureContainer((container) => 25 | { 26 | // SettingContext 27 | { 28 | // Register 29 | container.RegisterType().As() 30 | 31 | // Start 32 | .OnActivated((handler) => 33 | { 34 | handler.Instance.Start(); 35 | }) 36 | 37 | // Lifetime 38 | .AutoActivate().SingleInstance(); 39 | } 40 | }); 41 | 42 | 43 | // Class 44 | public class SettingContext 45 | { 46 | // Methods 47 | public void Start() 48 | { 49 | // Execute 50 | Console.WriteLine("SettingContext Started"); 51 | } 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /src/CLK.NetCoreLab.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33815.320 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HostedServiceLab", "HostedServiceLab\HostedServiceLab.csproj", "{B5BE33EE-9256-48E1-90DE-0CE34CC0C67B}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ObserverLab", "ObserverLab\ObserverLab.csproj", "{DCB3AB03-65E2-4DFC-8CEF-6B184BE78E68}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiagnosticSourceLab", "DiagnosticSourceLab\DiagnosticSourceLab.csproj", "{E8D1C4A0-D004-4DD7-BC96-E9E06DD34EEC}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetryLab", "OpenTelemetryLab\OpenTelemetryLab.csproj", "{206765B6-9307-4708-B0FA-6EF9BF57AF6E}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ActivitySourceLab", "ActivitySourceLab\ActivitySourceLab.csproj", "{987F3083-E4A9-468C-B4BA-0B3F230A98AA}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TraceContextLab", "TraceContextLab\TraceContextLab.csproj", "{EB958D50-6DE1-45E3-84CD-549887DC8FA2}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TraceContextLab.SubService", "TraceContextLab.SubService\TraceContextLab.SubService.csproj", "{75444640-D8AB-4FA2-8B36-088245971DE2}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RegisterModuleLab", "RegisterModuleLab\RegisterModuleLab.csproj", "{23DB179A-15C3-45F4-BA2D-7E48CA7085CC}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "00.Shared", "00.Shared", "{291105FC-F6CD-4BE1-AE6A-6CAFF50A3F0E}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TemplateLab", "TemplateLab\TemplateLab.csproj", "{5F101EA2-4448-4A1C-9359-FB79BE09D601}" 25 | EndProject 26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoActivateLab", "AutoActivateLab\AutoActivateLab.csproj", "{CD4C8995-21BE-44D6-AE80-0BFC6CEC376A}" 27 | EndProject 28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConfigurationLab", "ConfigurationLab\ConfigurationLab.csproj", "{2B9A9984-12C5-4013-90F6-C367985BCCD1}" 29 | EndProject 30 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QuartzLab", "QuartzLab\QuartzLab.csproj", "{5A2CEAF5-0A0F-46EC-B91A-729149C14F98}" 31 | EndProject 32 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OptionsLab", "OptionsLab\OptionsLab.csproj", "{5F689877-D493-4DD0-9E39-EFCA0F51DA10}" 33 | EndProject 34 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProgramServiceLab", "ProgramServiceLab\ProgramServiceLab.csproj", "{77C38232-D8E6-43D6-9D00-BD0E353BCE19}" 35 | EndProject 36 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Autofac", "Autofac", "{1585447F-7C5A-412D-ADD3-D5EA2AD6B296}" 37 | EndProject 38 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OpenTelemetry", "OpenTelemetry", "{648C029D-80A0-4605-A861-913038CEEF4F}" 39 | EndProject 40 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NamedServiceLab", "NamedServiceLab\NamedServiceLab.csproj", "{FB7D68E8-4ABC-4A1D-8714-52302B884819}" 41 | EndProject 42 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WithParameterLab", "WithParameterLab\WithParameterLab.csproj", "{D473F64E-FA5A-450A-93AC-8C2C10DD2407}" 43 | EndProject 44 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "02.Kernel", "02.Kernel", "{1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB}" 45 | EndProject 46 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "01.Application", "01.Application", "{7D1F2CD5-8837-4517-ABA9-94DE9B1F004F}" 47 | EndProject 48 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RemoveServiceLab", "RemoveServiceLab\RemoveServiceLab.csproj", "{55076ECB-D130-4838-A591-933CC98A72B6}" 49 | EndProject 50 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "HostedService", "HostedService", "{993C9A06-1729-42A6-968D-25CF7BEE7AF0}" 51 | EndProject 52 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ServiceCollection", "ServiceCollection", "{F0B8D212-A433-4952-8350-3EFEB5303F0B}" 53 | EndProject 54 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Configuration", "Configuration", "{1E87AA45-5CDC-4963-B460-E246378680DA}" 55 | EndProject 56 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Logging", "Logging", "{2C9FEAEA-AF73-47D7-A1FC-FE9096FF9B33}" 57 | EndProject 58 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggerLab", "LoggerLab\LoggerLab.csproj", "{7F0D026B-8004-4F45-A9CF-9E419C1F370E}" 59 | EndProject 60 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Options", "Options", "{931F63FF-9D08-461D-B63D-A0668BD7EBD5}" 61 | EndProject 62 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggerLab.NLog", "LoggerLab.NLog\LoggerLab.NLog.csproj", "{D9AEE19D-67FB-49BA-9344-6DB13CC8EDC1}" 63 | EndProject 64 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LoggerLab.Log4net", "LoggerLab.Log4net\LoggerLab.Log4net.csproj", "{ADD9D687-51EB-41E7-8926-9C904BCD696E}" 65 | EndProject 66 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoggerLab.Serilog", "LoggerLab.Serilog\LoggerLab.Serilog.csproj", "{79B3EADB-0392-4A6D-BBCF-328CAF3F1279}" 67 | EndProject 68 | Global 69 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 70 | Debug|Any CPU = Debug|Any CPU 71 | Release|Any CPU = Release|Any CPU 72 | EndGlobalSection 73 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 74 | {B5BE33EE-9256-48E1-90DE-0CE34CC0C67B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 75 | {B5BE33EE-9256-48E1-90DE-0CE34CC0C67B}.Debug|Any CPU.Build.0 = Debug|Any CPU 76 | {B5BE33EE-9256-48E1-90DE-0CE34CC0C67B}.Release|Any CPU.ActiveCfg = Release|Any CPU 77 | {B5BE33EE-9256-48E1-90DE-0CE34CC0C67B}.Release|Any CPU.Build.0 = Release|Any CPU 78 | {DCB3AB03-65E2-4DFC-8CEF-6B184BE78E68}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 79 | {DCB3AB03-65E2-4DFC-8CEF-6B184BE78E68}.Debug|Any CPU.Build.0 = Debug|Any CPU 80 | {DCB3AB03-65E2-4DFC-8CEF-6B184BE78E68}.Release|Any CPU.ActiveCfg = Release|Any CPU 81 | {DCB3AB03-65E2-4DFC-8CEF-6B184BE78E68}.Release|Any CPU.Build.0 = Release|Any CPU 82 | {E8D1C4A0-D004-4DD7-BC96-E9E06DD34EEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 83 | {E8D1C4A0-D004-4DD7-BC96-E9E06DD34EEC}.Debug|Any CPU.Build.0 = Debug|Any CPU 84 | {E8D1C4A0-D004-4DD7-BC96-E9E06DD34EEC}.Release|Any CPU.ActiveCfg = Release|Any CPU 85 | {E8D1C4A0-D004-4DD7-BC96-E9E06DD34EEC}.Release|Any CPU.Build.0 = Release|Any CPU 86 | {206765B6-9307-4708-B0FA-6EF9BF57AF6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 87 | {206765B6-9307-4708-B0FA-6EF9BF57AF6E}.Debug|Any CPU.Build.0 = Debug|Any CPU 88 | {206765B6-9307-4708-B0FA-6EF9BF57AF6E}.Release|Any CPU.ActiveCfg = Release|Any CPU 89 | {206765B6-9307-4708-B0FA-6EF9BF57AF6E}.Release|Any CPU.Build.0 = Release|Any CPU 90 | {987F3083-E4A9-468C-B4BA-0B3F230A98AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 91 | {987F3083-E4A9-468C-B4BA-0B3F230A98AA}.Debug|Any CPU.Build.0 = Debug|Any CPU 92 | {987F3083-E4A9-468C-B4BA-0B3F230A98AA}.Release|Any CPU.ActiveCfg = Release|Any CPU 93 | {987F3083-E4A9-468C-B4BA-0B3F230A98AA}.Release|Any CPU.Build.0 = Release|Any CPU 94 | {EB958D50-6DE1-45E3-84CD-549887DC8FA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 95 | {EB958D50-6DE1-45E3-84CD-549887DC8FA2}.Debug|Any CPU.Build.0 = Debug|Any CPU 96 | {EB958D50-6DE1-45E3-84CD-549887DC8FA2}.Release|Any CPU.ActiveCfg = Release|Any CPU 97 | {EB958D50-6DE1-45E3-84CD-549887DC8FA2}.Release|Any CPU.Build.0 = Release|Any CPU 98 | {75444640-D8AB-4FA2-8B36-088245971DE2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 99 | {75444640-D8AB-4FA2-8B36-088245971DE2}.Debug|Any CPU.Build.0 = Debug|Any CPU 100 | {75444640-D8AB-4FA2-8B36-088245971DE2}.Release|Any CPU.ActiveCfg = Release|Any CPU 101 | {75444640-D8AB-4FA2-8B36-088245971DE2}.Release|Any CPU.Build.0 = Release|Any CPU 102 | {23DB179A-15C3-45F4-BA2D-7E48CA7085CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 103 | {23DB179A-15C3-45F4-BA2D-7E48CA7085CC}.Debug|Any CPU.Build.0 = Debug|Any CPU 104 | {23DB179A-15C3-45F4-BA2D-7E48CA7085CC}.Release|Any CPU.ActiveCfg = Release|Any CPU 105 | {23DB179A-15C3-45F4-BA2D-7E48CA7085CC}.Release|Any CPU.Build.0 = Release|Any CPU 106 | {5F101EA2-4448-4A1C-9359-FB79BE09D601}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 107 | {5F101EA2-4448-4A1C-9359-FB79BE09D601}.Debug|Any CPU.Build.0 = Debug|Any CPU 108 | {5F101EA2-4448-4A1C-9359-FB79BE09D601}.Release|Any CPU.ActiveCfg = Release|Any CPU 109 | {5F101EA2-4448-4A1C-9359-FB79BE09D601}.Release|Any CPU.Build.0 = Release|Any CPU 110 | {CD4C8995-21BE-44D6-AE80-0BFC6CEC376A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 111 | {CD4C8995-21BE-44D6-AE80-0BFC6CEC376A}.Debug|Any CPU.Build.0 = Debug|Any CPU 112 | {CD4C8995-21BE-44D6-AE80-0BFC6CEC376A}.Release|Any CPU.ActiveCfg = Release|Any CPU 113 | {CD4C8995-21BE-44D6-AE80-0BFC6CEC376A}.Release|Any CPU.Build.0 = Release|Any CPU 114 | {2B9A9984-12C5-4013-90F6-C367985BCCD1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 115 | {2B9A9984-12C5-4013-90F6-C367985BCCD1}.Debug|Any CPU.Build.0 = Debug|Any CPU 116 | {2B9A9984-12C5-4013-90F6-C367985BCCD1}.Release|Any CPU.ActiveCfg = Release|Any CPU 117 | {2B9A9984-12C5-4013-90F6-C367985BCCD1}.Release|Any CPU.Build.0 = Release|Any CPU 118 | {5A2CEAF5-0A0F-46EC-B91A-729149C14F98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 119 | {5A2CEAF5-0A0F-46EC-B91A-729149C14F98}.Debug|Any CPU.Build.0 = Debug|Any CPU 120 | {5A2CEAF5-0A0F-46EC-B91A-729149C14F98}.Release|Any CPU.ActiveCfg = Release|Any CPU 121 | {5A2CEAF5-0A0F-46EC-B91A-729149C14F98}.Release|Any CPU.Build.0 = Release|Any CPU 122 | {5F689877-D493-4DD0-9E39-EFCA0F51DA10}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 123 | {5F689877-D493-4DD0-9E39-EFCA0F51DA10}.Debug|Any CPU.Build.0 = Debug|Any CPU 124 | {5F689877-D493-4DD0-9E39-EFCA0F51DA10}.Release|Any CPU.ActiveCfg = Release|Any CPU 125 | {5F689877-D493-4DD0-9E39-EFCA0F51DA10}.Release|Any CPU.Build.0 = Release|Any CPU 126 | {77C38232-D8E6-43D6-9D00-BD0E353BCE19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 127 | {77C38232-D8E6-43D6-9D00-BD0E353BCE19}.Debug|Any CPU.Build.0 = Debug|Any CPU 128 | {77C38232-D8E6-43D6-9D00-BD0E353BCE19}.Release|Any CPU.ActiveCfg = Release|Any CPU 129 | {77C38232-D8E6-43D6-9D00-BD0E353BCE19}.Release|Any CPU.Build.0 = Release|Any CPU 130 | {FB7D68E8-4ABC-4A1D-8714-52302B884819}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 131 | {FB7D68E8-4ABC-4A1D-8714-52302B884819}.Debug|Any CPU.Build.0 = Debug|Any CPU 132 | {FB7D68E8-4ABC-4A1D-8714-52302B884819}.Release|Any CPU.ActiveCfg = Release|Any CPU 133 | {FB7D68E8-4ABC-4A1D-8714-52302B884819}.Release|Any CPU.Build.0 = Release|Any CPU 134 | {D473F64E-FA5A-450A-93AC-8C2C10DD2407}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 135 | {D473F64E-FA5A-450A-93AC-8C2C10DD2407}.Debug|Any CPU.Build.0 = Debug|Any CPU 136 | {D473F64E-FA5A-450A-93AC-8C2C10DD2407}.Release|Any CPU.ActiveCfg = Release|Any CPU 137 | {D473F64E-FA5A-450A-93AC-8C2C10DD2407}.Release|Any CPU.Build.0 = Release|Any CPU 138 | {55076ECB-D130-4838-A591-933CC98A72B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 139 | {55076ECB-D130-4838-A591-933CC98A72B6}.Debug|Any CPU.Build.0 = Debug|Any CPU 140 | {55076ECB-D130-4838-A591-933CC98A72B6}.Release|Any CPU.ActiveCfg = Release|Any CPU 141 | {55076ECB-D130-4838-A591-933CC98A72B6}.Release|Any CPU.Build.0 = Release|Any CPU 142 | {7F0D026B-8004-4F45-A9CF-9E419C1F370E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 143 | {7F0D026B-8004-4F45-A9CF-9E419C1F370E}.Debug|Any CPU.Build.0 = Debug|Any CPU 144 | {7F0D026B-8004-4F45-A9CF-9E419C1F370E}.Release|Any CPU.ActiveCfg = Release|Any CPU 145 | {7F0D026B-8004-4F45-A9CF-9E419C1F370E}.Release|Any CPU.Build.0 = Release|Any CPU 146 | {D9AEE19D-67FB-49BA-9344-6DB13CC8EDC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 147 | {D9AEE19D-67FB-49BA-9344-6DB13CC8EDC1}.Debug|Any CPU.Build.0 = Debug|Any CPU 148 | {D9AEE19D-67FB-49BA-9344-6DB13CC8EDC1}.Release|Any CPU.ActiveCfg = Release|Any CPU 149 | {D9AEE19D-67FB-49BA-9344-6DB13CC8EDC1}.Release|Any CPU.Build.0 = Release|Any CPU 150 | {ADD9D687-51EB-41E7-8926-9C904BCD696E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 151 | {ADD9D687-51EB-41E7-8926-9C904BCD696E}.Debug|Any CPU.Build.0 = Debug|Any CPU 152 | {ADD9D687-51EB-41E7-8926-9C904BCD696E}.Release|Any CPU.ActiveCfg = Release|Any CPU 153 | {ADD9D687-51EB-41E7-8926-9C904BCD696E}.Release|Any CPU.Build.0 = Release|Any CPU 154 | {79B3EADB-0392-4A6D-BBCF-328CAF3F1279}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 155 | {79B3EADB-0392-4A6D-BBCF-328CAF3F1279}.Debug|Any CPU.Build.0 = Debug|Any CPU 156 | {79B3EADB-0392-4A6D-BBCF-328CAF3F1279}.Release|Any CPU.ActiveCfg = Release|Any CPU 157 | {79B3EADB-0392-4A6D-BBCF-328CAF3F1279}.Release|Any CPU.Build.0 = Release|Any CPU 158 | EndGlobalSection 159 | GlobalSection(SolutionProperties) = preSolution 160 | HideSolutionNode = FALSE 161 | EndGlobalSection 162 | GlobalSection(NestedProjects) = preSolution 163 | {B5BE33EE-9256-48E1-90DE-0CE34CC0C67B} = {993C9A06-1729-42A6-968D-25CF7BEE7AF0} 164 | {DCB3AB03-65E2-4DFC-8CEF-6B184BE78E68} = {648C029D-80A0-4605-A861-913038CEEF4F} 165 | {E8D1C4A0-D004-4DD7-BC96-E9E06DD34EEC} = {648C029D-80A0-4605-A861-913038CEEF4F} 166 | {206765B6-9307-4708-B0FA-6EF9BF57AF6E} = {648C029D-80A0-4605-A861-913038CEEF4F} 167 | {987F3083-E4A9-468C-B4BA-0B3F230A98AA} = {648C029D-80A0-4605-A861-913038CEEF4F} 168 | {EB958D50-6DE1-45E3-84CD-549887DC8FA2} = {648C029D-80A0-4605-A861-913038CEEF4F} 169 | {75444640-D8AB-4FA2-8B36-088245971DE2} = {648C029D-80A0-4605-A861-913038CEEF4F} 170 | {23DB179A-15C3-45F4-BA2D-7E48CA7085CC} = {1585447F-7C5A-412D-ADD3-D5EA2AD6B296} 171 | {5F101EA2-4448-4A1C-9359-FB79BE09D601} = {291105FC-F6CD-4BE1-AE6A-6CAFF50A3F0E} 172 | {CD4C8995-21BE-44D6-AE80-0BFC6CEC376A} = {1585447F-7C5A-412D-ADD3-D5EA2AD6B296} 173 | {2B9A9984-12C5-4013-90F6-C367985BCCD1} = {1E87AA45-5CDC-4963-B460-E246378680DA} 174 | {5A2CEAF5-0A0F-46EC-B91A-729149C14F98} = {7D1F2CD5-8837-4517-ABA9-94DE9B1F004F} 175 | {5F689877-D493-4DD0-9E39-EFCA0F51DA10} = {931F63FF-9D08-461D-B63D-A0668BD7EBD5} 176 | {77C38232-D8E6-43D6-9D00-BD0E353BCE19} = {993C9A06-1729-42A6-968D-25CF7BEE7AF0} 177 | {1585447F-7C5A-412D-ADD3-D5EA2AD6B296} = {1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB} 178 | {648C029D-80A0-4605-A861-913038CEEF4F} = {7D1F2CD5-8837-4517-ABA9-94DE9B1F004F} 179 | {FB7D68E8-4ABC-4A1D-8714-52302B884819} = {1585447F-7C5A-412D-ADD3-D5EA2AD6B296} 180 | {D473F64E-FA5A-450A-93AC-8C2C10DD2407} = {1585447F-7C5A-412D-ADD3-D5EA2AD6B296} 181 | {55076ECB-D130-4838-A591-933CC98A72B6} = {F0B8D212-A433-4952-8350-3EFEB5303F0B} 182 | {993C9A06-1729-42A6-968D-25CF7BEE7AF0} = {1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB} 183 | {F0B8D212-A433-4952-8350-3EFEB5303F0B} = {1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB} 184 | {1E87AA45-5CDC-4963-B460-E246378680DA} = {1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB} 185 | {2C9FEAEA-AF73-47D7-A1FC-FE9096FF9B33} = {1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB} 186 | {7F0D026B-8004-4F45-A9CF-9E419C1F370E} = {2C9FEAEA-AF73-47D7-A1FC-FE9096FF9B33} 187 | {931F63FF-9D08-461D-B63D-A0668BD7EBD5} = {1A9CEE07-8171-4B2F-BAA6-8D55505BC4EB} 188 | {D9AEE19D-67FB-49BA-9344-6DB13CC8EDC1} = {2C9FEAEA-AF73-47D7-A1FC-FE9096FF9B33} 189 | {ADD9D687-51EB-41E7-8926-9C904BCD696E} = {2C9FEAEA-AF73-47D7-A1FC-FE9096FF9B33} 190 | {79B3EADB-0392-4A6D-BBCF-328CAF3F1279} = {2C9FEAEA-AF73-47D7-A1FC-FE9096FF9B33} 191 | EndGlobalSection 192 | GlobalSection(ExtensibilityGlobals) = postSolution 193 | SolutionGuid = {D258BC6B-DA7B-460C-A772-4E72B345F41B} 194 | EndGlobalSection 195 | EndGlobal 196 | -------------------------------------------------------------------------------- /src/ConfigurationLab/ConfigurationLab.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | PreserveNewest 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/ConfigurationLab/FileSetting.json: -------------------------------------------------------------------------------- 1 | { 2 | "Service01": { 3 | "Id": "File_Id01", 4 | "Name": "File_Name01" 5 | }, 6 | "Setting01":"File_Setting01" 7 | } -------------------------------------------------------------------------------- /src/ConfigurationLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Hosting; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace ConfigurationLab 11 | { 12 | public class Program 13 | { 14 | // Methods 15 | public static void Main(string[] args) 16 | { 17 | CreateHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IHostBuilder CreateHostBuilder(string[] args) => 21 | Host.CreateDefaultBuilder(args) 22 | .ConfigureAppConfiguration((hostContext, configuration) => 23 | { 24 | // File 25 | configuration.AddJsonFile(Path.Combine(AppContext.BaseDirectory, "FileSetting.json")); 26 | 27 | // Memory 28 | configuration.AddInMemoryCollection(new Dictionary() 29 | { 30 | {"service02:Id","Memory_Id02"}, 31 | {"service02:Name","Memory_Name02"}, 32 | {"Setting02","Memory_Setting02"} 33 | }); 34 | }) 35 | .ConfigureServices((services) => 36 | { 37 | // ProgramService 38 | services.AddHostedService(); 39 | }); 40 | 41 | 42 | // Class 43 | public class ProgramService : BackgroundService 44 | { 45 | // Fields 46 | private readonly IConfiguration _configuration = null; 47 | 48 | 49 | // Constructors 50 | public ProgramService(IConfiguration configuration) 51 | { 52 | #region Contracts 53 | 54 | if (configuration == null) throw new ArgumentException(nameof(configuration)); 55 | 56 | #endregion 57 | 58 | // Default 59 | _configuration = configuration; 60 | } 61 | 62 | 63 | // Methods 64 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 65 | { 66 | return Task.Run(() => 67 | { 68 | // File 69 | { 70 | // Service01 71 | var service01 = _configuration.Bind("service01"); 72 | Console.WriteLine($"service01.Id = {service01.Id}"); 73 | Console.WriteLine($"service01.Name= {service01.Name}"); 74 | 75 | // Setting01 76 | var setting01 = _configuration.GetValue("Setting01"); 77 | Console.WriteLine($"setting01 = {setting01}"); 78 | } 79 | Console.WriteLine(); 80 | 81 | // Memory 82 | { 83 | // Service02 84 | var service02 = _configuration.Bind("service02"); 85 | Console.WriteLine($"service02.Id = {service02.Id}"); 86 | Console.WriteLine($"service02.Name= {service02.Name}"); 87 | 88 | // Setting02 89 | var setting02 = _configuration.GetValue("Setting02"); 90 | Console.WriteLine($"setting02 = {setting02}"); 91 | } 92 | Console.WriteLine(); 93 | }); 94 | } 95 | } 96 | 97 | public class ServiceSetting 98 | { 99 | // Properties 100 | public string Id { get; set; } 101 | 102 | public string Name { get; set; } 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /src/ConfigurationLab/Utilities/ConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace ConfigurationLab 10 | { 11 | public static class ConfigurationExtensions 12 | { 13 | // Methods 14 | public static T Bind(this IConfiguration configuration, string key) where T : class, new() 15 | { 16 | #region Contracts 17 | 18 | if (configuration == null) throw new ArgumentException(nameof(configuration)); 19 | if (string.IsNullOrEmpty(key) == true) throw new ArgumentException(nameof(key)); 20 | 21 | #endregion 22 | 23 | // Create 24 | var value = new T(); 25 | 26 | // Bind 27 | configuration.Bind(key, value); 28 | 29 | // Return 30 | return value; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/DiagnosticSourceLab/DiagnosticSourceLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/DiagnosticSourceLab/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | 5 | namespace DiagnosticSourceLab 6 | { 7 | public class Program 8 | { 9 | // Fields 10 | private static DiagnosticSource _diagnosticSource = new DiagnosticListener("CLK.DiagnosticSourceLab"); 11 | 12 | 13 | // Methods 14 | public static void Main(string[] args) 15 | { 16 | // Subscribe 17 | DiagnosticListener.AllListeners.Subscribe(new DiagnosticSourceSubscriber("CLK.DiagnosticSourceLab")); 18 | 19 | // Diagnostic 20 | { 21 | // Pay 22 | var activityName01 = "Pay"; 23 | if (_diagnosticSource.IsEnabled(activityName01) == true) 24 | { 25 | _diagnosticSource.Write(activityName01, new { User = "Clark" }); 26 | } 27 | 28 | // Print 29 | var activityName02 = "Print"; 30 | if (_diagnosticSource.IsEnabled(activityName02) == true) 31 | { 32 | _diagnosticSource.Write(activityName02, new { User = "Jane" }); 33 | } 34 | } 35 | } 36 | 37 | 38 | // Class 39 | public class DiagnosticSourceSubscriber : IObserver 40 | { 41 | // Fields 42 | private readonly string _diagnosticSourceName = null; 43 | 44 | private readonly DiagnosticExporter _diagnosticExporter = new DiagnosticExporter(); 45 | 46 | 47 | // Constructors 48 | public DiagnosticSourceSubscriber(string diagnosticSourceName) 49 | { 50 | #region Contracts 51 | 52 | if (string.IsNullOrEmpty(diagnosticSourceName) == true) throw new ArgumentException(nameof(diagnosticSourceName)); 53 | 54 | #endregion 55 | 56 | // Default 57 | _diagnosticSourceName = diagnosticSourceName; 58 | } 59 | 60 | 61 | // Methods 62 | public void OnNext(DiagnosticListener diagnosticSource) 63 | { 64 | #region Contracts 65 | 66 | if (diagnosticSource == null) throw new ArgumentException(nameof(diagnosticSource)); 67 | 68 | #endregion 69 | 70 | // Require 71 | if (diagnosticSource.Name != _diagnosticSourceName) return; 72 | 73 | // Subscribe 74 | diagnosticSource.Subscribe(_diagnosticExporter); 75 | } 76 | 77 | public void OnCompleted() { } 78 | 79 | public void OnError(Exception error) { } 80 | } 81 | 82 | public class DiagnosticExporter : IObserver> 83 | { 84 | // Methods 85 | public void OnNext(KeyValuePair diagnostic) 86 | { 87 | // Display 88 | Console.WriteLine($"Activity: Name={diagnostic.Key}, Printload={diagnostic.Value}"); 89 | } 90 | 91 | public void OnCompleted() { } 92 | 93 | public void OnError(Exception error) { } 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/HostedServiceLab/HostedServiceLab.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/HostedServiceLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Reflection; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace HostedServiceLab 11 | { 12 | public class Program 13 | { 14 | // Methods 15 | public static void Main(string[] args) 16 | { 17 | CreateHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IHostBuilder CreateHostBuilder(string[] args) => 21 | Host.CreateDefaultBuilder(args) 22 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 23 | .ConfigureContainer((container) => 24 | { 25 | // HostedService 26 | container.RegisterAssemblyTypes(Assembly.GetEntryAssembly()).As(); 27 | }); 28 | 29 | 30 | // Class 31 | public class ProgramService : IHostedService 32 | { 33 | // Fields 34 | private readonly ILogger _logger = null; 35 | 36 | 37 | // Constructors 38 | public ProgramService(ILogger logger) 39 | { 40 | #region Contracts 41 | 42 | if (logger == null) throw new ArgumentException(); 43 | 44 | #endregion 45 | 46 | // Default 47 | _logger = logger; 48 | } 49 | 50 | 51 | // Methods 52 | public Task StartAsync(CancellationToken cancellationToken) 53 | { 54 | // Notify 55 | Console.WriteLine("ProgramService:StartAsync"); 56 | 57 | // Return 58 | return Task.CompletedTask; 59 | } 60 | 61 | public Task StopAsync(CancellationToken cancellationToken) 62 | { 63 | // Notify 64 | Console.WriteLine("ProgramService:StopAsync"); 65 | 66 | // Return 67 | return Task.CompletedTask; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/LoggerLab.Log4net.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | PreserveNewest 11 | 12 | 13 | PreserveNewest 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace LoggerLab.Log4net 9 | { 10 | public class Program 11 | { 12 | // Methods 13 | public static void Main(string[] args) 14 | { 15 | CreateHostBuilder(args).Build().Run(); 16 | } 17 | 18 | public static IHostBuilder CreateHostBuilder(string[] args) => 19 | Host.CreateDefaultBuilder(args) 20 | .ConfigureServices((services) => 21 | { 22 | // Logging 23 | services.AddLogging((builder) => 24 | { 25 | // Environment 26 | log4net.GlobalContext.Properties["ApplicationName"] = System.Reflection.Assembly.GetEntryAssembly().GetName().Name; 27 | 28 | // Log4net 29 | builder.AddLog4net("log4net.config"); 30 | }); 31 | 32 | // ProgramService 33 | services.AddHostedService(); 34 | }); 35 | 36 | 37 | // Class 38 | public class ProgramService : BackgroundService 39 | { 40 | // Fields 41 | private readonly ILogger _logger; 42 | 43 | 44 | // Constructors 45 | public ProgramService(ILogger logger) 46 | { 47 | #region Contracts 48 | 49 | if (logger == null) throw new ArgumentException(nameof(logger)); 50 | 51 | #endregion 52 | 53 | // Default 54 | _logger = logger; 55 | } 56 | 57 | 58 | // Methods 59 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 60 | { 61 | return Task.Run(() => 62 | { 63 | // Logger-Message 64 | Console.WriteLine("=====Logger-Message====="); 65 | _logger.LogTrace("Trace Message"); 66 | _logger.LogDebug("Debug Message"); 67 | _logger.LogInformation("Information Message"); 68 | _logger.LogWarning("Warning Message"); 69 | _logger.LogError("Error Message"); 70 | _logger.LogCritical("Critical Message"); 71 | Console.WriteLine("\n"); 72 | 73 | // Logger-Exception 74 | Console.WriteLine("=====Logger-Exception====="); 75 | _logger.LogTrace(this.GetException("Trace Exception"), "Trace Message"); 76 | _logger.LogDebug(this.GetException("Debug Exception"), "Debug Message"); 77 | _logger.LogInformation(this.GetException("Information Exception"), "Information Message"); 78 | _logger.LogWarning(this.GetException("Warning Exception"), "Warning Message"); 79 | _logger.LogError(this.GetException("Error Exception"), "Error Message"); 80 | _logger.LogCritical(this.GetException("Critical Exception"), "Critical Message"); 81 | Console.WriteLine("\n"); 82 | }); 83 | } 84 | 85 | private Exception GetException(string message) 86 | { 87 | #region Contracts 88 | 89 | if (string.IsNullOrEmpty(message) == true) throw new ArgumentException(nameof(message)); 90 | 91 | #endregion 92 | 93 | try 94 | { 95 | // Throw 96 | throw new Exception(message); 97 | } 98 | catch (Exception ex) 99 | { 100 | // Return 101 | return ex; 102 | } 103 | } 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/Utilities/ConfigureExtensions.cs: -------------------------------------------------------------------------------- 1 | using log4net; 2 | using log4net.Config; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace LoggerLab.Log4net 12 | { 13 | public static class ConfigureExtensions 14 | { 15 | public static ILoggingBuilder AddLog4net(this ILoggingBuilder builder, string configFileName = "log4net.config") 16 | { 17 | #region Contracts 18 | 19 | if (builder == null) throw new ArgumentException(nameof(builder)); 20 | if (string.IsNullOrEmpty(configFileName) == true) throw new ArgumentException(nameof(configFileName)); 21 | 22 | #endregion 23 | 24 | // Log4netProvider 25 | builder.AddProvider(new Log4netLoggerProvider(configFileName)); 26 | 27 | // Return 28 | return builder; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/Utilities/Log4netLogger.cs: -------------------------------------------------------------------------------- 1 | using log4net; 2 | using Microsoft.Extensions.Logging; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace LoggerLab.Log4net 10 | { 11 | public class Log4netLogger : ILogger 12 | { 13 | // Fields 14 | private readonly ILog _logger = null; 15 | 16 | 17 | // Constructors 18 | internal Log4netLogger(string categoryName) 19 | { 20 | #region Contracts 21 | 22 | if (string.IsNullOrEmpty(categoryName) == true) throw new ArgumentException(nameof(categoryName)); 23 | 24 | #endregion 25 | 26 | // Logger 27 | _logger = LogManager.GetLogger(categoryName); 28 | if (_logger == null) throw new InvalidOperationException("_logger=null"); 29 | } 30 | 31 | 32 | // Methods 33 | public IDisposable BeginScope(TState state) 34 | { 35 | // Return 36 | return null; 37 | } 38 | 39 | public bool IsEnabled(LogLevel logLevel) 40 | { 41 | // Mapping 42 | switch (logLevel) 43 | { 44 | case LogLevel.Trace: return _logger.IsDebugEnabled; 45 | case LogLevel.Debug: return _logger.IsDebugEnabled; 46 | case LogLevel.Information: return _logger.IsInfoEnabled; 47 | case LogLevel.Warning: return _logger.IsWarnEnabled; 48 | case LogLevel.Error: return _logger.IsErrorEnabled; 49 | case LogLevel.Critical: return _logger.IsFatalEnabled; 50 | case LogLevel.None: return false; 51 | default: throw new InvalidOperationException($"Unknown logLevel: {nameof(logLevel)}={logLevel}"); 52 | } 53 | } 54 | 55 | public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) 56 | { 57 | // Require 58 | if (this.IsEnabled(logLevel) == false) return; 59 | if (formatter == null) throw new InvalidOperationException($"{nameof(formatter)}=null"); 60 | 61 | // Message 62 | var message = formatter(state, exception); 63 | if (string.IsNullOrEmpty(message) == true) message = string.Empty; 64 | 65 | // Write 66 | switch (logLevel) 67 | { 68 | case LogLevel.Trace: _logger.Debug(message, exception); break; 69 | case LogLevel.Debug: _logger.Debug(message, exception); break; 70 | case LogLevel.Information: _logger.Info(message, exception); break; 71 | case LogLevel.Warning: _logger.Warn(message, exception); break; 72 | case LogLevel.Error: _logger.Error(message, exception); break; 73 | case LogLevel.Critical: _logger.Fatal(message, exception); break; 74 | case LogLevel.None: break; 75 | default: throw new InvalidOperationException($"Unknown logLevel: {nameof(logLevel)}={logLevel}"); 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/Utilities/Log4netProvider.cs: -------------------------------------------------------------------------------- 1 | using log4net; 2 | using log4net.Config; 3 | using log4net.Repository; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.IO; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace LoggerLab.Log4net 13 | { 14 | public class Log4netLoggerProvider : ILoggerProvider 15 | { 16 | // Fields 17 | private readonly ILoggerRepository _loggerRepository = null; 18 | 19 | 20 | // Constructors 21 | public Log4netLoggerProvider(string configFileName) 22 | { 23 | #region Contracts 24 | 25 | if (string.IsNullOrEmpty(configFileName) == true) throw new ArgumentException(nameof(configFileName)); 26 | 27 | #endregion 28 | 29 | // LoggerRepository 30 | _loggerRepository = this.CreateLoggerRepository(configFileName); 31 | if (_loggerRepository == null) throw new InvalidOperationException($"{nameof(_loggerRepository)}=null"); 32 | } 33 | 34 | public void Dispose() 35 | { 36 | // Shutdown 37 | _loggerRepository.Shutdown(); 38 | } 39 | 40 | 41 | // Methods 42 | public ILogger CreateLogger(string categoryName) 43 | { 44 | #region Contracts 45 | 46 | if (string.IsNullOrEmpty(categoryName) == true) throw new ArgumentException(nameof(categoryName)); 47 | 48 | #endregion 49 | 50 | // Create 51 | return new Log4netLogger(categoryName); 52 | } 53 | 54 | private ILoggerRepository CreateLoggerRepository(string configFileName) 55 | { 56 | #region Contracts 57 | 58 | if (string.IsNullOrEmpty(configFileName) == true) throw new ArgumentException(nameof(configFileName)); 59 | 60 | #endregion 61 | 62 | // LoggerRepository 63 | var loggerRepository = LogManager.GetRepository(); 64 | if (loggerRepository == null) throw new InvalidOperationException($"{nameof(loggerRepository)}=null"); 65 | 66 | // Configure 67 | XmlConfigurator.Configure(loggerRepository, new FileInfo(configFileName)); 68 | 69 | // Return 70 | return loggerRepository; 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "LoggerLab.*": "Trace" 6 | }, 7 | "EventLog": { 8 | "LogLevel": { 9 | "Default": "None" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /src/LoggerLab.Log4net/log4net.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/LoggerLab.NLog/LoggerLab.NLog.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | PreserveNewest 11 | 12 | 13 | PreserveNewest 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/LoggerLab.NLog/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using NLog.Extensions.Logging; 5 | using System; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Linq; 9 | using NLogLib = NLog; 10 | 11 | namespace LoggerLab.NLog 12 | { 13 | public class Program 14 | { 15 | // Methods 16 | public static void Main(string[] args) 17 | { 18 | CreateHostBuilder(args).Build().Run(); 19 | } 20 | 21 | public static IHostBuilder CreateHostBuilder(string[] args) => 22 | Host.CreateDefaultBuilder(args) 23 | .ConfigureServices((services) => 24 | { 25 | // Logging 26 | services.AddLogging((builder) => 27 | { 28 | // Environment 29 | NLogLib.GlobalDiagnosticsContext.Set("ApplicationName", System.Reflection.Assembly.GetEntryAssembly().GetName().Name); 30 | 31 | // NLog 32 | builder.AddNLog("nlog.config"); 33 | }); 34 | 35 | // ProgramService 36 | services.AddHostedService(); 37 | }); 38 | 39 | 40 | // Class 41 | public class ProgramService : BackgroundService 42 | { 43 | // Fields 44 | private readonly ILogger _logger; 45 | 46 | 47 | // Constructors 48 | public ProgramService(ILogger logger) 49 | { 50 | #region Contracts 51 | 52 | if (logger == null) throw new ArgumentException(nameof(logger)); 53 | 54 | #endregion 55 | 56 | // Default 57 | _logger = logger; 58 | } 59 | 60 | 61 | // Methods 62 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 63 | { 64 | return Task.Run(() => 65 | { 66 | // Logger-Message 67 | Console.WriteLine("=====Logger-Message====="); 68 | _logger.LogTrace("Trace Message"); 69 | _logger.LogDebug("Debug Message"); 70 | _logger.LogInformation("Information Message"); 71 | _logger.LogWarning("Warning Message"); 72 | _logger.LogError("Error Message"); 73 | _logger.LogCritical("Critical Message"); 74 | Console.WriteLine("\n"); 75 | 76 | // Logger-Exception 77 | Console.WriteLine("=====Logger-Exception====="); 78 | _logger.LogTrace(this.GetException("Trace Exception"), "Trace Message"); 79 | _logger.LogDebug(this.GetException("Debug Exception"), "Debug Message"); 80 | _logger.LogInformation(this.GetException("Information Exception"), "Information Message"); 81 | _logger.LogWarning(this.GetException("Warning Exception"), "Warning Message"); 82 | _logger.LogError(this.GetException("Error Exception"), "Error Message"); 83 | _logger.LogCritical(this.GetException("Critical Exception"), "Critical Message"); 84 | Console.WriteLine("\n"); 85 | }); 86 | } 87 | 88 | private Exception GetException(string message) 89 | { 90 | #region Contracts 91 | 92 | if (string.IsNullOrEmpty(message) == true) throw new ArgumentException(nameof(message)); 93 | 94 | #endregion 95 | 96 | try 97 | { 98 | // Throw 99 | throw new Exception(message); 100 | } 101 | catch (Exception ex) 102 | { 103 | // Return 104 | return ex; 105 | } 106 | } 107 | } 108 | } 109 | } -------------------------------------------------------------------------------- /src/LoggerLab.NLog/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "LoggerLab.*": "Trace" 6 | }, 7 | "EventLog": { 8 | "LogLevel": { 9 | "Default": "None" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /src/LoggerLab.NLog/nlog.config: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/LoggerLab.Serilog/LoggerLab.Serilog.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | PreserveNewest 11 | 12 | 13 | PreserveNewest 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/LoggerLab.Serilog/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Serilog; 8 | using Microsoft.Extensions.Configuration; 9 | using Serilog.Core; 10 | using Serilog.Extensions.Logging; 11 | 12 | namespace LoggerLab.Serilog 13 | { 14 | public class Program 15 | { 16 | // Methods 17 | public static void Main(string[] args) 18 | { 19 | CreateHostBuilder(args).Build().Run(); 20 | } 21 | 22 | public static IHostBuilder CreateHostBuilder(string[] args) => 23 | Host.CreateDefaultBuilder(args) 24 | .ConfigureServices((services) => 25 | { 26 | // Logging 27 | services.AddLogging((builder) => 28 | { 29 | // SerilogConfig 30 | var serilogConfig = new ConfigurationBuilder() 31 | .SetBasePath(System.IO.Directory.GetCurrentDirectory()) 32 | .AddJsonFile("serilog.json") 33 | .Build(); 34 | 35 | // Serilog 36 | Log.Logger = new LoggerConfiguration() 37 | .ReadFrom.Configuration(serilogConfig) 38 | .Enrich.WithThreadId() 39 | .Enrich.WithProperty("ApplicationName", System.Reflection.Assembly.GetEntryAssembly().GetName().Name) 40 | .CreateLogger(); 41 | 42 | // Serilog 43 | builder.AddProvider(new SerilogLoggerProvider()); 44 | }); 45 | 46 | // ProgramService 47 | services.AddHostedService(); 48 | }); 49 | 50 | 51 | // Class 52 | public class ProgramService : BackgroundService 53 | { 54 | // Fields 55 | private readonly Microsoft.Extensions.Logging.ILogger _logger; 56 | 57 | 58 | // Constructors 59 | public ProgramService(ILogger logger) 60 | { 61 | #region Contracts 62 | 63 | if (logger == null) throw new ArgumentException(nameof(logger)); 64 | 65 | #endregion 66 | 67 | // Default 68 | _logger = logger; 69 | } 70 | 71 | 72 | // Methods 73 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 74 | { 75 | return Task.Run(() => 76 | { 77 | // Logger-Message 78 | Console.WriteLine("=====Logger-Message====="); 79 | _logger.LogTrace("Trace Message"); 80 | _logger.LogDebug("Debug Message"); 81 | _logger.LogInformation("Information Message"); 82 | _logger.LogWarning("Warning Message"); 83 | _logger.LogError("Error Message"); 84 | _logger.LogCritical("Critical Message"); 85 | Console.WriteLine("\n"); 86 | 87 | // Logger-Exception 88 | Console.WriteLine("=====Logger-Exception====="); 89 | _logger.LogTrace(this.GetException("Trace Exception"), "Trace Message"); 90 | _logger.LogDebug(this.GetException("Debug Exception"), "Debug Message"); 91 | _logger.LogInformation(this.GetException("Information Exception"), "Information Message"); 92 | _logger.LogWarning(this.GetException("Warning Exception"), "Warning Message"); 93 | _logger.LogError(this.GetException("Error Exception"), "Error Message"); 94 | _logger.LogCritical(this.GetException("Critical Exception"), "Critical Message"); 95 | Console.WriteLine("\n"); 96 | }); 97 | } 98 | 99 | private Exception GetException(string message) 100 | { 101 | #region Contracts 102 | 103 | if (string.IsNullOrEmpty(message) == true) throw new ArgumentException(nameof(message)); 104 | 105 | #endregion 106 | 107 | try 108 | { 109 | // Throw 110 | throw new Exception(message); 111 | } 112 | catch (Exception ex) 113 | { 114 | // Return 115 | return ex; 116 | } 117 | } 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /src/LoggerLab.Serilog/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "LoggerLab.*": "Trace" 6 | }, 7 | "EventLog": { 8 | "LogLevel": { 9 | "Default": "None" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /src/LoggerLab.Serilog/serilog.json: -------------------------------------------------------------------------------- 1 | { 2 | "Serilog": { 3 | "MinimumLevel": "Verbose", 4 | "WriteTo": [ 5 | { 6 | "Name": "File", 7 | "Args": { 8 | "path": ".\\log\\log-.log", 9 | "rollingInterval": "Day", 10 | "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{ThreadId}] {Level} {SourceContext} - {Message}{NewLine}{Exception}" 11 | } 12 | } 13 | ] 14 | } 15 | } -------------------------------------------------------------------------------- /src/LoggerLab/LoggerLab.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | PreserveNewest 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/LoggerLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Configuration; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Hosting; 4 | using Microsoft.Extensions.Logging; 5 | using System; 6 | using System.IO; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace LoggerLab 11 | { 12 | public class Program 13 | { 14 | // Methods 15 | public static void Main(string[] args) 16 | { 17 | CreateHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IHostBuilder CreateHostBuilder(string[] args) => 21 | Host.CreateDefaultBuilder(args) 22 | .ConfigureServices((services) => 23 | { 24 | // ProgramService 25 | services.AddHostedService(); 26 | }); 27 | 28 | 29 | // Class 30 | public class ProgramService : BackgroundService 31 | { 32 | // Fields 33 | private readonly ILogger _logger; 34 | 35 | 36 | // Constructors 37 | public ProgramService(ILogger logger) 38 | { 39 | #region Contracts 40 | 41 | if (logger == null) throw new ArgumentException(nameof(logger)); 42 | 43 | #endregion 44 | 45 | // Default 46 | _logger = logger; 47 | } 48 | 49 | 50 | // Methods 51 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 52 | { 53 | return Task.Run(() => 54 | { 55 | // Logger-Message 56 | Console.WriteLine("=====Logger-Message====="); 57 | _logger.LogTrace("Trace Message"); 58 | _logger.LogDebug("Debug Message"); 59 | _logger.LogInformation("Information Message"); 60 | _logger.LogWarning("Warning Message"); 61 | _logger.LogError("Error Message"); 62 | _logger.LogCritical("Critical Message"); 63 | Console.WriteLine("\n"); 64 | 65 | // Logger-Exception 66 | Console.WriteLine("=====Logger-Exception====="); 67 | _logger.LogTrace(this.GetException("Trace Exception"), "Trace Message"); 68 | _logger.LogDebug(this.GetException("Debug Exception"), "Debug Message"); 69 | _logger.LogInformation(this.GetException("Information Exception"), "Information Message"); 70 | _logger.LogWarning(this.GetException("Warning Exception"), "Warning Message"); 71 | _logger.LogError(this.GetException("Error Exception"), "Error Message"); 72 | _logger.LogCritical(this.GetException("Critical Exception"), "Critical Message"); 73 | Console.WriteLine("\n"); 74 | }); 75 | } 76 | 77 | private Exception GetException(string message) 78 | { 79 | #region Contracts 80 | 81 | if (string.IsNullOrEmpty(message) == true) throw new ArgumentException(nameof(message)); 82 | 83 | #endregion 84 | 85 | try 86 | { 87 | // Throw 88 | throw new Exception(message); 89 | } 90 | catch (Exception ex) 91 | { 92 | // Return 93 | return ex; 94 | } 95 | } 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /src/LoggerLab/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning", 5 | "LoggerLab.*": "Trace" 6 | }, 7 | "EventLog": { 8 | "LogLevel": { 9 | "Default": "None" 10 | } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /src/NamedServiceLab/NamedServiceLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/NamedServiceLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using System; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using Microsoft.Extensions.Configuration; 9 | using System.Collections.Generic; 10 | 11 | namespace NamedServiceLab 12 | { 13 | public class Program 14 | { 15 | // Methods 16 | public static void Main(string[] args) 17 | { 18 | CreateHostBuilder(args).Build().Run(); 19 | } 20 | 21 | public static IHostBuilder CreateHostBuilder(string[] args) => 22 | Host.CreateDefaultBuilder(args) 23 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 24 | .ConfigureServices((services) => 25 | { 26 | // ProgramService 27 | services.AddHostedService(); 28 | }) 29 | .ConfigureAppConfiguration((hostContext, configuration) => 30 | { 31 | // Memory 32 | configuration.AddInMemoryCollection(new Dictionary() 33 | { 34 | {"SettingContextName","AAA"} 35 | }); 36 | }) 37 | .ConfigureContainer((container) => 38 | { 39 | // Register 40 | container.Register(componentContext => 41 | { 42 | // Configuration 43 | var configuration = componentContext.Resolve(); 44 | if (configuration == null) throw new InvalidOperationException($"{nameof(configuration)}=null"); 45 | 46 | // ServiceName 47 | var serviceName = configuration.GetValue("SettingContextName"); 48 | if (string.IsNullOrEmpty(serviceName) == true) throw new InvalidOperationException($"{nameof(serviceName)}=null"); 49 | 50 | // Resolve 51 | return componentContext.ResolveNamed(serviceName); 52 | }); 53 | container.RegisterType().Named("AAA"); 54 | container.RegisterType().Named("BBB"); 55 | }); 56 | 57 | 58 | // Class 59 | public class ProgramService : BackgroundService 60 | { 61 | // Fields 62 | private readonly SettingContext _settingContext = null; 63 | 64 | 65 | // Constructors 66 | public ProgramService(SettingContext settingContext) 67 | { 68 | #region Contracts 69 | 70 | if (settingContext == null) throw new ArgumentException(nameof(settingContext)); 71 | 72 | #endregion 73 | 74 | // Default 75 | _settingContext = settingContext; 76 | } 77 | 78 | 79 | // Methods 80 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 81 | { 82 | return Task.Run(() => 83 | { 84 | // Execute 85 | Console.WriteLine(_settingContext.GetValue()); 86 | }); 87 | } 88 | } 89 | 90 | public interface SettingContext 91 | { 92 | // Methods 93 | string GetValue(); 94 | } 95 | 96 | public class SettingContextAAA : SettingContext 97 | { 98 | // Methods 99 | public string GetValue() 100 | { 101 | // Return 102 | return "Hello World! : AAA"; 103 | } 104 | } 105 | 106 | public class SettingContextBBB : SettingContext 107 | { 108 | // Methods 109 | public string GetValue() 110 | { 111 | // Return 112 | return "Hello World! : BBB"; 113 | } 114 | } 115 | } 116 | } -------------------------------------------------------------------------------- /src/ObserverLab/ObserverLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/ObserverLab/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics.Contracts; 4 | using System.Linq; 5 | 6 | namespace ObserverLab 7 | { 8 | public class Program 9 | { 10 | // Methods 11 | public static void Main(string[] args) 12 | { 13 | // Publisher 14 | using (var locationPublisher = new LocationPublisher()) 15 | { 16 | // Observer 17 | var locationObserver = new LocationObserver(); 18 | 19 | // Subscribe 20 | var locationObserverUnsubscriber = locationPublisher.Subscribe(locationObserver); 21 | locationPublisher.Write(new Location() { X = 1, Y = 1 }); 22 | locationPublisher.Write(new Location() { X = 2, Y = 2 }); 23 | 24 | // Unsubscribe 25 | locationObserverUnsubscriber.Dispose(); 26 | locationPublisher.Write(new Location() { X = 3, Y = 3 }); 27 | } 28 | } 29 | 30 | 31 | // Class 32 | public class Location 33 | { 34 | // Properties 35 | public int X { get; set; } 36 | 37 | public int Y { get; set; } 38 | } 39 | 40 | public class LocationPublisher : Observable 41 | { 42 | 43 | } 44 | 45 | public class LocationObserver : IObserver 46 | { 47 | // Methods 48 | public void OnNext(Location location) 49 | { 50 | #region Contracts 51 | 52 | if (location == null) throw new ArgumentException(nameof(location)); 53 | 54 | #endregion 55 | 56 | // Display 57 | Console.WriteLine($"Location: X={location.X}, Y={location.Y}"); 58 | } 59 | 60 | public void OnCompleted() 61 | { 62 | // Nothing 63 | 64 | } 65 | 66 | public void OnError(Exception error) 67 | { 68 | #region Contracts 69 | 70 | if (error == null) throw new ArgumentException(nameof(error)); 71 | 72 | #endregion 73 | 74 | // Nothing 75 | 76 | } 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/ObserverLab/Utilities/Observable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace ObserverLab 8 | { 9 | public class Observable : IObservable, IDisposable 10 | { 11 | // Fields 12 | private readonly object _syncRoot = new object(); 13 | 14 | private List> _observerList = new List>(); 15 | 16 | private List> _observerListCache = null; 17 | 18 | 19 | // Constructors 20 | public Observable() 21 | { 22 | 23 | } 24 | 25 | public void Dispose() 26 | { 27 | // ObserverList 28 | List> observerList = null; 29 | 30 | // Sync 31 | lock (_syncRoot) 32 | { 33 | // Require 34 | if (_observerList == null) return; 35 | 36 | // Clear 37 | observerList = _observerList; 38 | _observerList = null; 39 | 40 | // Cache 41 | _observerListCache = null; 42 | } 43 | 44 | // Notify 45 | foreach (var observer in observerList) 46 | { 47 | // OnCompleted 48 | observer.OnCompleted(); 49 | } 50 | } 51 | 52 | 53 | // Methods 54 | public void Write(T value) 55 | { 56 | // ObserverList 57 | var observerList = _observerListCache; 58 | if (observerList == null) 59 | { 60 | // Sync 61 | lock (_syncRoot) 62 | { 63 | // Require 64 | if (_observerList == null) throw new ObjectDisposedException(this.GetType().Name); 65 | 66 | // Cache 67 | if (_observerListCache == null) 68 | { 69 | _observerListCache = _observerList.ToList(); 70 | } 71 | observerList = _observerListCache; 72 | } 73 | } 74 | 75 | // Notify 76 | foreach (var observer in observerList) 77 | { 78 | // OnNext 79 | observer.OnNext(value); 80 | } 81 | } 82 | 83 | public IDisposable Subscribe(IObserver observer) 84 | { 85 | #region Contracts 86 | 87 | if (observer == null) throw new ArgumentException(nameof(observer)); 88 | 89 | #endregion 90 | 91 | // Sync 92 | lock (_syncRoot) 93 | { 94 | // Require 95 | if (_observerList == null) throw new ObjectDisposedException(this.GetType().Name); 96 | 97 | // Add 98 | if (_observerList.Contains(observer) == false) 99 | { 100 | _observerList.Add(observer); 101 | } 102 | 103 | // Cache 104 | _observerListCache = null; 105 | } 106 | 107 | // Return 108 | return new Subscription(() => this.Unsubscribe(observer)); 109 | } 110 | 111 | private void Unsubscribe(IObserver observer) 112 | { 113 | #region Contracts 114 | 115 | if (observer == null) throw new ArgumentException(nameof(observer)); 116 | 117 | #endregion 118 | 119 | // Sync 120 | lock (_syncRoot) 121 | { 122 | // Require 123 | if (_observerList == null) return; 124 | 125 | // Remove 126 | if (_observerList.Contains(observer) == true) 127 | { 128 | _observerList.Remove(observer); 129 | } 130 | 131 | // Cache 132 | _observerListCache = null; 133 | } 134 | } 135 | 136 | 137 | // Class 138 | private class Subscription : IDisposable 139 | { 140 | // Fields 141 | private readonly Action _removeAction = null; 142 | 143 | 144 | // Constructors 145 | public Subscription(Action removeAction) 146 | { 147 | #region Contracts 148 | 149 | if (removeAction == null) throw new ArgumentException(nameof(removeAction)); 150 | 151 | #endregion 152 | 153 | // Default 154 | _removeAction = removeAction; 155 | } 156 | 157 | public void Dispose() 158 | { 159 | // Execute 160 | _removeAction(); 161 | } 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/OpenTelemetryLab/OpenTelemetryLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/OpenTelemetryLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Diagnostics; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using OpenTelemetry; 8 | using OpenTelemetry.Trace; 9 | using OpenTelemetry.Exporter; 10 | using OpenTelemetry.Resources; 11 | 12 | namespace OpenTelemetryLab 13 | { 14 | public class Program 15 | { 16 | // Methods 17 | public static void Main(string[] args) 18 | { 19 | CreateHostBuilder(args).Build().Run(); 20 | } 21 | 22 | public static IHostBuilder CreateHostBuilder(string[] args) => 23 | Host.CreateDefaultBuilder(args) 24 | .ConfigureServices((services)=> 25 | { 26 | // OpenTelemetry 27 | services.AddOpenTelemetryTracing((tracerProvider) => 28 | { 29 | // Resource 30 | tracerProvider.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("CLK-OpenTelemetryLab-Service")); 31 | 32 | // Source 33 | tracerProvider.AddSource("CLK.OpenTelemetryLab.MainModule"); 34 | 35 | // Exporter 36 | tracerProvider.AddConsoleExporter(); 37 | tracerProvider.AddJaegerExporter(options => 38 | { 39 | options.AgentHost = "localhost"; 40 | }); 41 | }); 42 | 43 | // ProgramService 44 | services.AddHostedService(); 45 | }); 46 | 47 | 48 | // Class 49 | public class ProgramService : BackgroundService 50 | { 51 | // Fields 52 | private static ActivitySource _activitySource = new ActivitySource("CLK.OpenTelemetryLab.MainModule"); 53 | 54 | 55 | // Methods 56 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 57 | { 58 | return Task.Run(() => { 59 | 60 | // Pay 61 | using (var payActivity = _activitySource.StartActivity("Pay", ActivityKind.Internal)) 62 | { 63 | // Execute 64 | Thread.Sleep(1000); 65 | payActivity?.SetTag("User", "Clark"); 66 | 67 | // Print 68 | using (var printActivity = _activitySource.StartActivity("Print", ActivityKind.Internal)) 69 | { 70 | // Execute 71 | Thread.Sleep(1000); 72 | printActivity?.SetTag("User", "Jane"); 73 | } 74 | 75 | // Sleep 76 | Thread.Sleep(1000); 77 | } 78 | 79 | }); 80 | } 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/OptionsLab/OptionsLab.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | PreserveNewest 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/OptionsLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Options; 6 | using System; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace OptionsLab 11 | { 12 | public class Program 13 | { 14 | // Methods 15 | public static void Main(string[] args) 16 | { 17 | CreateHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IHostBuilder CreateHostBuilder(string[] args) => 21 | Host.CreateDefaultBuilder(args) 22 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 23 | .ConfigureServices((hostContext, services) => 24 | { 25 | // ProgramService 26 | services.AddHostedService(); 27 | 28 | // ProgramOptions 29 | { 30 | // Configure-Setting 31 | services.Configure((options) => 32 | { 33 | options.Value001 = "Config001"; 34 | }); 35 | 36 | // Configure-IConfiguration 37 | services.Configure 38 | ( 39 | hostContext.Configuration.GetSection("ProgramOptions") 40 | ); 41 | 42 | // Configure-DI 43 | services.AddOptions().Configure((options, hostEnvironment) => 44 | { 45 | options.Value003 = hostEnvironment.ApplicationName; 46 | }); 47 | 48 | // IConfigureOptions 49 | services.AddSingleton> 50 | ( 51 | new ConfigureNamedOptions(Options.DefaultName, (options) => 52 | { 53 | options.Value004 = "Config004"; 54 | }) 55 | ); 56 | } 57 | }) 58 | .ConfigureContainer((container) => 59 | { 60 | // ProgramOptions 61 | { 62 | // IConfigureOptions 63 | container.RegisterInstance> 64 | ( 65 | new ConfigureNamedOptions(Options.DefaultName, (options) => 66 | { 67 | options.Value005 = "Config005"; 68 | }) 69 | ); 70 | } 71 | }); 72 | 73 | 74 | // Class 75 | public class ProgramService : BackgroundService 76 | { 77 | // Fields 78 | private readonly IOptions _options = null; 79 | 80 | 81 | // Constructors 82 | public ProgramService(IOptions options) 83 | { 84 | #region Contracts 85 | 86 | if (options == null) throw new ArgumentException(nameof(options)); 87 | 88 | #endregion 89 | 90 | // Default 91 | _options = options; 92 | } 93 | 94 | 95 | // Methods 96 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 97 | { 98 | return Task.Run(() => 99 | { 100 | // Display 101 | Console.WriteLine($"_options.Value001={_options.Value?.Value001}"); 102 | Console.WriteLine($"_options.Value002={_options.Value?.Value002}"); 103 | Console.WriteLine($"_options.Value003={_options.Value?.Value003}"); 104 | Console.WriteLine($"_options.Value004={_options.Value?.Value004}"); 105 | Console.WriteLine($"_options.Value005={_options.Value?.Value005}"); 106 | }); 107 | } 108 | } 109 | 110 | public class ProgramOptions 111 | { 112 | // Properties 113 | public string Value001 { get; set; } = "Default001"; 114 | 115 | public string Value002 { get; set; } = "Default002"; 116 | 117 | public string Value003 { get; set; } = "Default003"; 118 | 119 | public string Value004 { get; set; } = "Default004"; 120 | 121 | public string Value005 { get; set; } = "Default005"; 122 | } 123 | } 124 | } -------------------------------------------------------------------------------- /src/OptionsLab/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ProgramOptions": { 3 | "Value002": "Config002" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/ProgramServiceLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | 6 | namespace ProgramServiceLab 7 | { 8 | public class Program 9 | { 10 | // Methods 11 | public static void Run(ILogger logger, IHostEnvironment hostEnvironment) 12 | { 13 | #region Contracts 14 | 15 | if (logger == null) throw new ArgumentException(nameof(logger)); 16 | if (hostEnvironment == null) throw new ArgumentException(nameof(hostEnvironment)); 17 | 18 | #endregion 19 | 20 | // Execute 21 | logger.LogWarning($"Hello World!"); 22 | logger.LogWarning(hostEnvironment.ContentRootPath); 23 | } 24 | 25 | public static void Main(string[] args) 26 | { 27 | CreateHostBuilder(args).Build().Run(); 28 | } 29 | 30 | public static IHostBuilder CreateHostBuilder(string[] args) => 31 | Host.CreateDefaultBuilder(args) 32 | .ConfigureServices((services) => 33 | { 34 | services.AddProgramService(); 35 | }); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/ProgramServiceLab/ProgramServiceLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/ProgramServiceLab/Utilities/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace ProgramServiceLab 11 | { 12 | public static class ServiceCollectionExtensions 13 | { 14 | // Methods 15 | public static IServiceCollection AddProgramService(this IServiceCollection services) where TProgramService : class 16 | { 17 | #region Contracts 18 | 19 | if (services == null) throw new ArgumentException(nameof(services)); 20 | 21 | #endregion 22 | 23 | // Add 24 | services.AddSingleton>(); 25 | 26 | // Return 27 | return services; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/ProgramServiceLab/Utilities/Extensions/TypeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace ProgramServiceLab 9 | { 10 | public static class TypeExtensions 11 | { 12 | // Methods 13 | public static ConstructorInfo FindConstructor(this Type instanceType) 14 | { 15 | #region Contracts 16 | 17 | if (instanceType == null) throw new ArgumentException(nameof(instanceType)); 18 | 19 | #endregion 20 | 21 | // Require 22 | if (instanceType.IsAbstract == true) throw new InvalidOperationException($"The '{instanceType.FullName}' is abstract."); 23 | 24 | // ConstructorInfoList 25 | var constructorInfoList = instanceType.GetConstructors().ToList(); 26 | if (constructorInfoList.Count == 0) throw new InvalidOperationException($"Not having constructor in the type '{instanceType.FullName}' is not supported."); 27 | if (constructorInfoList.Count >= 2) throw new InvalidOperationException($"Having multiple constructor in the type '{instanceType.FullName}' is not supported."); 28 | 29 | // ConstructorInfo 30 | var constructorInfo = constructorInfoList.First(); 31 | if (constructorInfo == null) throw new InvalidOperationException($"{nameof(constructorInfo)}=null"); 32 | 33 | // Return 34 | return constructorInfo; 35 | } 36 | 37 | public static MethodInfo FindMethod(this Type instanceType, string methodName) 38 | { 39 | #region Contracts 40 | 41 | if (instanceType == null) throw new ArgumentException(nameof(instanceType)); 42 | if (string.IsNullOrEmpty(methodName) == true) throw new ArgumentException(nameof(methodName)); 43 | 44 | #endregion 45 | 46 | // MethodInfoList 47 | var methodInfoList = instanceType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).Where(method => method.Name.Equals(methodName, StringComparison.OrdinalIgnoreCase)).ToList(); 48 | if (methodInfoList.Count == 0) return null; 49 | if (methodInfoList.Count >= 2) throw new InvalidOperationException($"Having multiple overloads of method '{methodName}' in the type '{instanceType.FullName}' is not supported."); 50 | 51 | // MethodInfo 52 | var methodInfo = methodInfoList.First(); 53 | if (methodInfo == null) throw new InvalidOperationException($"{nameof(methodInfo)}=null"); 54 | 55 | // Return 56 | return methodInfo; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/ProgramServiceLab/Utilities/ProgramService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace ProgramServiceLab 10 | { 11 | public class ProgramService : BackgroundService where TProgram : class 12 | { 13 | // Fields 14 | private readonly IServiceProvider _serviceProvider = null; 15 | 16 | private readonly IHostApplicationLifetime _hostApplicationLifetime = null; 17 | 18 | 19 | // Constructors 20 | public ProgramService(IServiceProvider serviceProvider, IHostApplicationLifetime hostApplicationLifetime) 21 | { 22 | #region Contracts 23 | 24 | if (serviceProvider == null) throw new ArgumentException(nameof(serviceProvider)); 25 | if (hostApplicationLifetime == null) throw new ArgumentException(nameof(hostApplicationLifetime)); 26 | 27 | #endregion 28 | 29 | // Default 30 | _serviceProvider = serviceProvider; 31 | _hostApplicationLifetime = hostApplicationLifetime; 32 | } 33 | 34 | 35 | // Methods 36 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 37 | { 38 | // Execute 39 | return Task.Run(() => 40 | { 41 | // Run 42 | ServiceActivator.ExecuteMethod(_serviceProvider, "Run"); 43 | 44 | // End 45 | _hostApplicationLifetime.StopApplication(); 46 | }); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/ProgramServiceLab/Utilities/ServiceActivator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace ProgramServiceLab 9 | { 10 | public class ServiceActivator 11 | { 12 | // Methods 13 | public static void ExecuteMethod(IServiceProvider serviceProvider, string methodName, Dictionary parameters = null) where TInstanceType : class 14 | { 15 | #region Contracts 16 | 17 | if (serviceProvider == null) throw new ArgumentException(nameof(serviceProvider)); 18 | if (string.IsNullOrEmpty(methodName) == true) throw new ArgumentException(nameof(methodName)); 19 | 20 | #endregion 21 | 22 | // ExecuteMethod 23 | ExecuteMethod(serviceProvider, methodName, parameters); 24 | } 25 | 26 | public static TResultType ExecuteMethod(IServiceProvider serviceProvider, string methodName, Dictionary parameters = null) where TInstanceType : class 27 | { 28 | #region Contracts 29 | 30 | if (serviceProvider == null) throw new ArgumentException(nameof(serviceProvider)); 31 | if (string.IsNullOrEmpty(methodName) == true) throw new ArgumentException(nameof(methodName)); 32 | 33 | #endregion 34 | 35 | // Parameters 36 | if (parameters == null) parameters = new Dictionary(); 37 | 38 | // Instance 39 | var instance = CreateInstance(serviceProvider); 40 | if (instance == null) throw new InvalidOperationException($"{nameof(instance)}=null"); 41 | 42 | // MethodInfo 43 | var methodInfo = typeof(TInstanceType).FindMethod(methodName); 44 | if (methodInfo == null) throw new InvalidOperationException($"{nameof(methodInfo)}=null"); 45 | 46 | // ParameterValueArray 47 | var parameterValueArray = CreateParameterValueArray(serviceProvider, methodInfo.GetParameters(), parameters); 48 | if (parameterValueArray == null) throw new InvalidOperationException($"{nameof(parameterValueArray)}=null"); 49 | 50 | // ExecuteMethod 51 | return (TResultType)methodInfo.Invoke 52 | ( 53 | obj: instance, 54 | parameters: parameterValueArray, 55 | invokeAttr: BindingFlags.DoNotWrapExceptions, 56 | binder: null, 57 | culture: null 58 | ); 59 | } 60 | 61 | public static TInstanceType CreateInstance(IServiceProvider serviceProvider, Dictionary parameters = null) where TInstanceType : class 62 | { 63 | #region Contracts 64 | 65 | if (serviceProvider == null) throw new ArgumentException(nameof(serviceProvider)); 66 | 67 | #endregion 68 | 69 | // Parameters 70 | if (parameters == null) parameters = new Dictionary(); 71 | 72 | // ConstructorInfo 73 | var constructorInfo = typeof(TInstanceType).FindConstructor(); 74 | if (constructorInfo == null) throw new InvalidOperationException($"{nameof(constructorInfo)}=null"); 75 | 76 | // ParameterValueArray 77 | var parameterValueArray = CreateParameterValueArray(serviceProvider, constructorInfo.GetParameters(), parameters); 78 | if (parameterValueArray == null) throw new InvalidOperationException($"{nameof(parameterValueArray)}=null"); 79 | 80 | // Create 81 | return (TInstanceType)constructorInfo.Invoke 82 | ( 83 | parameters: parameterValueArray, 84 | invokeAttr: BindingFlags.DoNotWrapExceptions, 85 | culture: null, 86 | binder: null 87 | ); 88 | } 89 | 90 | private static object[] CreateParameterValueArray(IServiceProvider serviceProvider, ParameterInfo[] parameterInfoArray, Dictionary parameters) 91 | { 92 | #region Contracts 93 | 94 | if (serviceProvider == null) throw new ArgumentException(nameof(serviceProvider)); 95 | if (parameterInfoArray == null) throw new ArgumentException(nameof(parameterInfoArray)); 96 | if (parameters == null) throw new ArgumentException(nameof(parameterInfoArray)); 97 | 98 | #endregion 99 | 100 | // ParameterValueArray 101 | var parameterValueArray = new object[parameterInfoArray.Length]; 102 | for (var i = 0; i < parameterInfoArray.Length; i++) 103 | { 104 | // ParameterInfo 105 | var parameterInfo = parameterInfoArray[i]; 106 | if (parameterInfo == null) throw new InvalidOperationException($"{nameof(parameterInfo)}=null"); 107 | 108 | // ParameterValue 109 | { 110 | // IServiceProvider 111 | if (parameterInfo.ParameterType == typeof(IServiceProvider)) { parameterValueArray[i] = serviceProvider; continue; } 112 | 113 | // Parameters 114 | if (parameters.ContainsKey(parameterInfo.Name) == true) { parameterValueArray[i] = parameters[parameterInfo.Name]; continue; } 115 | 116 | // Injection 117 | parameterValueArray[i] = serviceProvider.GetService(parameterInfo.ParameterType); continue; 118 | } 119 | } 120 | 121 | // Return 122 | return parameterValueArray; 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/QuartzLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Hosting; 5 | using Microsoft.Extensions.Logging; 6 | using Microsoft.Extensions.Options; 7 | using Quartz; 8 | using System; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | 12 | namespace QuartzLab 13 | { 14 | public class Program 15 | { 16 | // Methods 17 | public static void Main(string[] args) 18 | { 19 | CreateHostBuilder(args).Build().Run(); 20 | } 21 | 22 | public static IHostBuilder CreateHostBuilder(string[] args) => 23 | Host.CreateDefaultBuilder(args) 24 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 25 | .ConfigureServices((services) => 26 | { 27 | // Quartz 28 | services.AddQuartz(options => 29 | { 30 | // Setting 31 | options.UseMicrosoftDependencyInjectionScopedJobFactory(); 32 | 33 | // ScheduleJob 34 | options.ScheduleJob((trigger) => 35 | { 36 | // Trigger 37 | trigger.WithCronSchedule("0/5 * * * * ?"); 38 | }); 39 | }); 40 | services.AddQuartzHostedService(options => options.WaitForJobsToComplete = true); 41 | 42 | // ScheduleJob 43 | services.Configure((options) => 44 | { 45 | var jobKey = JobKey.Create(nameof(HelloWorldJob002)); 46 | options.AddJob(job => job.WithIdentity(jobKey)); 47 | options.AddTrigger(trigger => 48 | { 49 | trigger 50 | .WithIdentity($"{nameof(HelloWorldJob002)}-trigger") 51 | .ForJob(jobKey) 52 | .WithCronSchedule("0/5 * * * * ?") 53 | ; 54 | }); 55 | }); 56 | services.AddTransient(); 57 | }) 58 | .ConfigureContainer((container) => 59 | { 60 | // ScheduleJob 61 | container.RegisterInstance> 62 | ( 63 | new ConfigureNamedOptions(Options.DefaultName, (options) => 64 | { 65 | var jobKey = JobKey.Create(nameof(HelloWorldJob003)); 66 | options.AddJob(job => job.WithIdentity(jobKey)); 67 | options.AddTrigger(trigger => 68 | { 69 | trigger 70 | .WithIdentity($"{nameof(HelloWorldJob003)}-trigger") 71 | .ForJob(jobKey) 72 | .WithCronSchedule("0/5 * * * * ?") 73 | ; 74 | }); 75 | }) 76 | ); 77 | container.RegisterType(); 78 | }); 79 | 80 | 81 | // Class 82 | public class DisplayJob : IJob 83 | { 84 | // Fields 85 | private readonly ILogger _logger = null; 86 | 87 | 88 | // Constructors 89 | public DisplayJob(ILogger logger) 90 | { 91 | #region Contracts 92 | 93 | if (logger == null) throw new ArgumentException(nameof(logger)); 94 | 95 | #endregion 96 | 97 | // Default 98 | _logger = logger; 99 | } 100 | 101 | 102 | // Methods 103 | public Task Execute(IJobExecutionContext context) 104 | { 105 | #region Contracts 106 | 107 | if (context == null) throw new ArgumentException(nameof(context)); 108 | 109 | #endregion 110 | 111 | // Execute 112 | return Task.Run(() => 113 | { 114 | // Display 115 | _logger.LogWarning(this.GetType().Name); 116 | }); 117 | } 118 | } 119 | 120 | [DisallowConcurrentExecution] 121 | public class HelloWorldJob001 : DisplayJob 122 | { 123 | // Constructors 124 | public HelloWorldJob001(ILogger logger) : base(logger) { } 125 | } 126 | 127 | [DisallowConcurrentExecution] 128 | public class HelloWorldJob002 : DisplayJob 129 | { 130 | // Constructors 131 | public HelloWorldJob002(ILogger logger) : base(logger) { } 132 | } 133 | 134 | [DisallowConcurrentExecution] 135 | public class HelloWorldJob003 : DisplayJob 136 | { 137 | // Constructors 138 | public HelloWorldJob003(ILogger logger) : base(logger) { } 139 | } 140 | } 141 | } -------------------------------------------------------------------------------- /src/QuartzLab/QuartzLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/RegisterModuleLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using System; 7 | using System.Reflection; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace RegisterModuleLab 12 | { 13 | public class Program 14 | { 15 | // Methods 16 | public static void Main(string[] args) 17 | { 18 | CreateHostBuilder(args).Build().Run(); 19 | } 20 | 21 | public static IHostBuilder CreateHostBuilder(string[] args) => 22 | Host.CreateDefaultBuilder(args) 23 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 24 | .ConfigureContainer((container) => 25 | { 26 | // Module 27 | container.RegisterAssemblyModules(Assembly.GetEntryAssembly()); 28 | }) 29 | .ConfigureServices((services) => 30 | { 31 | // ProgramService 32 | services.AddHostedService(); 33 | }); 34 | 35 | 36 | // Class 37 | public class ProgramService : BackgroundService 38 | { 39 | // Fields 40 | private readonly SettingContext _settingContext = null; 41 | 42 | 43 | // Constructors 44 | public ProgramService(SettingContext settingContext) 45 | { 46 | #region Contracts 47 | 48 | if (settingContext == null) throw new ArgumentException(nameof(settingContext)); 49 | 50 | #endregion 51 | 52 | // Default 53 | _settingContext = settingContext; 54 | } 55 | 56 | 57 | // Methods 58 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 59 | { 60 | return Task.Run(() => 61 | { 62 | // Execute 63 | Console.WriteLine(_settingContext.GetValue()); 64 | }); 65 | } 66 | } 67 | 68 | public class SettingContext 69 | { 70 | // Methods 71 | public string GetValue() 72 | { 73 | // Return 74 | return "Hello World!"; 75 | } 76 | } 77 | 78 | public class SettingContextModule : Autofac.Module 79 | { 80 | // Methods 81 | protected override void Load(ContainerBuilder container) 82 | { 83 | #region Contracts 84 | 85 | if (container == null) throw new ArgumentException(nameof(container)); 86 | 87 | #endregion 88 | 89 | // SettingContext 90 | { 91 | // Register 92 | container.RegisterType().As(); 93 | } 94 | } 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /src/RegisterModuleLab/RegisterModuleLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/RemoveServiceLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Microsoft.Extensions.Logging.Console; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace RemoveServiceLab 9 | { 10 | public class Program 11 | { 12 | // Methods 13 | public static void Main(string[] args) 14 | { 15 | CreateHostBuilder(args).Build().Run(); 16 | } 17 | 18 | public static IHostBuilder CreateHostBuilder(string[] args) => 19 | Host.CreateDefaultBuilder(args) 20 | .ConfigureServices((services) => 21 | { 22 | // RemoveService 23 | services.RemoveService(); 24 | 25 | // ProgramService 26 | services.AddHostedService(); 27 | }); 28 | 29 | 30 | // Class 31 | public class ProgramService : BackgroundService 32 | { 33 | // Methods 34 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 35 | { 36 | return Task.Run(() => 37 | { 38 | // Execute 39 | Console.WriteLine("Hello World!"); 40 | }); 41 | } 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/RemoveServiceLab/RemoveServiceLab.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/RemoveServiceLab/Utilities/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace RemoveServiceLab 11 | { 12 | public static class ServiceCollectionExtensions 13 | { 14 | // Methods 15 | public static IServiceCollection RemoveService(this IServiceCollection services) where TService : class 16 | { 17 | #region Contracts 18 | 19 | if (services == null) throw new ArgumentException(nameof(services)); 20 | 21 | #endregion 22 | 23 | // ServiceDescriptor 24 | var serviceDescriptor = services.FirstOrDefault(o => o.ImplementationType == typeof(TService)); 25 | if (serviceDescriptor == null) return services; 26 | 27 | // Remove 28 | services.Remove(serviceDescriptor); 29 | 30 | // Return 31 | return services; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/TemplateLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace TemplateLab 8 | { 9 | public class Program 10 | { 11 | // Methods 12 | public static void Main(string[] args) 13 | { 14 | CreateHostBuilder(args).Build().Run(); 15 | } 16 | 17 | public static IHostBuilder CreateHostBuilder(string[] args) => 18 | Host.CreateDefaultBuilder(args) 19 | .ConfigureServices((services) => 20 | { 21 | // ProgramService 22 | services.AddHostedService(); 23 | }); 24 | 25 | 26 | // Class 27 | public class ProgramService : BackgroundService 28 | { 29 | // Methods 30 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 31 | { 32 | return Task.Run(() => 33 | { 34 | // Execute 35 | Console.WriteLine("Hello World!"); 36 | }); 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/TemplateLab/TemplateLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/TraceContextLab.SubService/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Diagnostics; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using OpenTelemetry; 8 | using OpenTelemetry.Trace; 9 | using OpenTelemetry.Exporter; 10 | using OpenTelemetry.Resources; 11 | using System.Net.Http; 12 | using System.Text; 13 | using System.Net; 14 | using System.IO; 15 | 16 | namespace TraceContextLab.SubService 17 | { 18 | public class Program 19 | { 20 | // Methods 21 | public static void Main(string[] args) 22 | { 23 | CreateHostBuilder(args).Build().Run(); 24 | } 25 | 26 | public static IHostBuilder CreateHostBuilder(string[] args) => 27 | Host.CreateDefaultBuilder(args) 28 | .ConfigureServices((services) => 29 | { 30 | // HttpClient 31 | services.AddHttpClient(); 32 | 33 | // OpenTelemetry 34 | services.AddOpenTelemetryTracing((tracerProvider) => 35 | { 36 | // Resource 37 | tracerProvider.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("CLK-TraceContextLab-SubService")); 38 | 39 | // Source 40 | tracerProvider.AddSource("CLK.TraceContextLab.SubModule"); 41 | 42 | // Exporter 43 | tracerProvider.AddConsoleExporter(); 44 | tracerProvider.AddJaegerExporter(options => 45 | { 46 | options.AgentHost = "localhost"; 47 | }); 48 | }); 49 | 50 | // ProgramService 51 | services.AddHostedService(); 52 | }); 53 | 54 | 55 | // Class 56 | public class ProgramService : BackgroundService 57 | { 58 | // Fields 59 | private static ActivitySource _activitySource = new ActivitySource("CLK.TraceContextLab.SubModule"); 60 | 61 | 62 | // Methods 63 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 64 | { 65 | return Task.Run(() => { 66 | 67 | // Variables 68 | HttpListener httpListener = null; 69 | HttpListenerContext httpContext = null; 70 | 71 | // Execute 72 | try 73 | { 74 | // HttpListener 75 | httpListener = new System.Net.HttpListener(); 76 | httpListener.Prefixes.Add(@"http://localhost:8080/"); 77 | httpListener.Start(); 78 | 79 | // Listen 80 | while (true) 81 | { 82 | httpContext = httpListener.GetContext(); 83 | if (httpContext != null) break; 84 | } 85 | 86 | // ParentContext 87 | ActivityContext parentContext = default; 88 | var traceParent = httpContext.Request.Headers["traceparent"]; 89 | var traceState = httpContext.Request.Headers["tracestate"]; 90 | if (string.IsNullOrEmpty(traceParent) == false) parentContext = ActivityContext.Parse(traceParent, traceState); 91 | 92 | // Calculate 93 | using (var calculateActivity = _activitySource.StartActivity("Calculate", ActivityKind.Server, parentContext)) 94 | { 95 | // Execute 96 | Thread.Sleep(1000); 97 | calculateActivity?.SetTag("Amount", "500"); 98 | } 99 | 100 | // Response 101 | httpContext.Response.StatusCode = 200; 102 | using (var streamWriter = new StreamWriter(httpContext.Response.OutputStream)) 103 | { 104 | streamWriter.Write(@"{amount:500}"); 105 | streamWriter.Close(); 106 | } 107 | httpContext.Response.Close(); 108 | } 109 | finally 110 | { 111 | // Dispose 112 | Thread.Sleep(1000); 113 | httpListener?.Stop(); 114 | httpListener?.Close(); 115 | } 116 | }); 117 | } 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/TraceContextLab.SubService/TraceContextLab.SubService.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/TraceContextLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using System; 4 | using System.Diagnostics; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using OpenTelemetry; 8 | using OpenTelemetry.Trace; 9 | using OpenTelemetry.Exporter; 10 | using OpenTelemetry.Resources; 11 | using System.Net.Http; 12 | using System.Text; 13 | 14 | namespace TraceContextLab 15 | { 16 | public class Program 17 | { 18 | // Methods 19 | public static void Main(string[] args) 20 | { 21 | CreateHostBuilder(args).Build().Run(); 22 | } 23 | 24 | public static IHostBuilder CreateHostBuilder(string[] args) => 25 | Host.CreateDefaultBuilder(args) 26 | .ConfigureServices((services) => 27 | { 28 | // HttpClient 29 | services.AddHttpClient(); 30 | 31 | // OpenTelemetry 32 | services.AddOpenTelemetryTracing((tracerProvider) => 33 | { 34 | // Resource 35 | tracerProvider.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("CLK-TraceContextLab-MainService")); 36 | 37 | // Source 38 | tracerProvider.AddSource("CLK.TraceContextLab.MainModule"); 39 | 40 | // Instrumentation 41 | //tracerProvider.AddHttpClientInstrumentation(); 42 | 43 | // Exporter 44 | tracerProvider.AddConsoleExporter(); 45 | tracerProvider.AddJaegerExporter(options => 46 | { 47 | options.AgentHost = "localhost"; 48 | }); 49 | }); 50 | 51 | // ProgramService 52 | services.AddHostedService(); 53 | }); 54 | 55 | 56 | // Class 57 | public class ProgramService : BackgroundService 58 | { 59 | // Fields 60 | private static ActivitySource _activitySource = new ActivitySource("CLK.TraceContextLab.MainModule"); 61 | 62 | private readonly IHttpClientFactory _httpClientFactory = null; 63 | 64 | 65 | // Constructors 66 | public ProgramService(IHttpClientFactory httpClientFactory) 67 | { 68 | #region Contracts 69 | 70 | if (httpClientFactory == null) throw new ArgumentException(nameof(httpClientFactory)); 71 | 72 | #endregion 73 | 74 | // Default 75 | _httpClientFactory = httpClientFactory; 76 | } 77 | 78 | 79 | // Methods 80 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 81 | { 82 | return Task.Run(() => { 83 | 84 | // Pay 85 | using (var payActivity = _activitySource.StartActivity("Pay", ActivityKind.Internal)) 86 | { 87 | // Execute 88 | Thread.Sleep(1000); 89 | payActivity?.SetTag("User", "Clark"); 90 | 91 | // Print 92 | using (var printActivity = _activitySource.StartActivity("Print", ActivityKind.Client)) 93 | { 94 | // Execute 95 | this.CallSubService("http://localhost:8080/"); 96 | printActivity?.SetTag("User", "Jane"); 97 | } 98 | 99 | // Sleep 100 | Thread.Sleep(1000); 101 | } 102 | }); 103 | } 104 | 105 | private void CallSubService(string requestUri) 106 | { 107 | #region Contracts 108 | 109 | if (string.IsNullOrEmpty(requestUri) == true) throw new ArgumentException(nameof(requestUri)); 110 | 111 | #endregion 112 | 113 | // SubService 114 | using (var httpClient = _httpClientFactory.CreateClient()) 115 | { 116 | // RequestContent 117 | var requestContent = new StringContent("{user:\"Clark\"}", Encoding.UTF8, "application/json"); 118 | if (requestContent == null) throw new InvalidOperationException($"{nameof(requestContent)}==null"); 119 | 120 | // Post 121 | var response = httpClient.PostAsync(requestUri, requestContent).GetAwaiter().GetResult(); 122 | if (response == null) throw new InvalidOperationException($"{nameof(response)}==null"); 123 | if (response.IsSuccessStatusCode == false) 124 | { 125 | var errorMessage = response.Content?.ReadAsStringAsync()?.GetAwaiter().GetResult()?.Trim(); 126 | if (string.IsNullOrEmpty(errorMessage) == false) throw new InvalidOperationException($"StatusCode={response.StatusCode}, ErrorMessage={errorMessage}"); 127 | } 128 | if (response.IsSuccessStatusCode == false) throw new InvalidOperationException($"StatusCode={response.StatusCode}"); 129 | 130 | // ResponseContent 131 | var responseContent = response.Content; 132 | if (responseContent == null) throw new InvalidOperationException($"{nameof(responseContent)}==null"); 133 | var responseContentString = responseContent.ReadAsStringAsync().GetAwaiter().GetResult(); 134 | if (string.IsNullOrEmpty(responseContentString) == true) throw new InvalidOperationException($"{nameof(responseContentString)}==null"); 135 | } 136 | } 137 | } 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/TraceContextLab/TraceContextLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/WithParameterLab/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Core; 3 | using Autofac.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Reflection; 10 | using System.Threading; 11 | using System.Threading.Tasks; 12 | 13 | namespace WithParameterLab 14 | { 15 | public class Program 16 | { 17 | // Methods 18 | public static void Main(string[] args) 19 | { 20 | CreateHostBuilder(args).Build().Run(); 21 | } 22 | 23 | public static IHostBuilder CreateHostBuilder(string[] args) => 24 | Host.CreateDefaultBuilder(args) 25 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 26 | .ConfigureServices((services) => 27 | { 28 | // ProgramService 29 | services.AddHostedService(); 30 | }) 31 | .ConfigureContainer((container) => 32 | { 33 | // SettingContext 34 | { 35 | // ParameterList 36 | var parameterList = new Dictionary(StringComparer.OrdinalIgnoreCase); 37 | parameterList.Add("AAA", "Data001"); 38 | parameterList.Add("BBB", "123"); 39 | 40 | // Register 41 | container.RegisterType().As().WithParameter 42 | ( 43 | // ParameterSelector 44 | (parameterInfo, componentContext) => 45 | { 46 | return parameterList.ContainsKey(parameterInfo.Name); 47 | }, 48 | 49 | // ValueProvider 50 | (parameterInfo, componentContext) => 51 | { 52 | return Convert.ChangeType(parameterList[parameterInfo.Name], parameterInfo.ParameterType); 53 | } 54 | ); 55 | } 56 | }); 57 | 58 | 59 | // Class 60 | public class ProgramService : BackgroundService 61 | { 62 | // Fields 63 | private readonly SettingContext _settingContext = null; 64 | 65 | 66 | // Constructors 67 | public ProgramService(SettingContext settingContext) 68 | { 69 | #region Contracts 70 | 71 | if (settingContext == null) throw new ArgumentException(nameof(settingContext)); 72 | 73 | #endregion 74 | 75 | // Default 76 | _settingContext = settingContext; 77 | } 78 | 79 | 80 | // Methods 81 | protected override Task ExecuteAsync(CancellationToken stoppingToken) 82 | { 83 | return Task.Run(() => 84 | { 85 | // Execute 86 | Console.WriteLine(_settingContext.GetValue()); 87 | }); 88 | } 89 | } 90 | 91 | public class SettingContext 92 | { 93 | // Constructors 94 | public SettingContext(string aaa, int bbb) 95 | { 96 | // Display 97 | Console.WriteLine($"aaa={aaa}"); 98 | Console.WriteLine($"bbb={bbb}"); 99 | } 100 | 101 | // Methods 102 | public string GetValue() 103 | { 104 | // Return 105 | return "Hello World!"; 106 | } 107 | } 108 | } 109 | } -------------------------------------------------------------------------------- /src/WithParameterLab/WithParameterLab.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | --------------------------------------------------------------------------------