---
# System prepended metadata

title: mod14
tags: [Core]

---

```csharp
// homecontroller.cs
public class HomeController : Controller
{
    readonly ILogger<HomeController> _logger; //field

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Home.Index...");

        return View();
    }
}
//=========================
// homecontroller.cs
public IActionResult Index()
{
    _logger.LogCritical("Log Message - Critical");
    _logger.LogError("Log Message - Error");
    _logger.LogWarning("Log Message - Warning");
    _logger.LogInformation("Log Message - Information");
    _logger.LogDebug("Log Message - Debug");
    _logger.LogTrace("Log Message - Trace");

    return View();
}
//=====================
// homecontroller.cs
public IActionResult Index()
{    

    //Console.WriteLine($"{DateTime.Now:yyyyMMdd-hh:mm:ss}");

    _logger.LogCritical("Log Message - Critical:{path} - {time:yyyyMMdd-hh:mm:ss}", 
        Request.Path, DateTime.Now);
    _logger.LogError("Log Message - Error:{path}", Request.Path);
    _logger.LogWarning("Log Message - Warning:{path}", Request.Path);
    _logger.LogInformation("Log Message - Information:{path}", Request.Path);
    _logger.LogDebug("Log Message - Debug:{path}", Request.Path);
    _logger.LogTrace("Log Message - Trace:{path}", Request.Path);



    return View();
}
//==================================
// MyLogEvents.cs
public class MyLogEvents
{
    public const int FormatError = 1000;
    public const int ArgumentNullError = 1001;
    public const int OverflowError = 1002;
}

// homecontroller.cs
[HttpPost]
public IActionResult Index(string number)
{
    try
    {
        int i = int.Parse(number);
        ViewBag.Message = $"Result: {i * i}";
    }
    catch (ArgumentNullException ex)
    {
        _logger.LogWarning(MyLogEvents.ArgumentNullError, ex, "Path:{path}", Request.Path);
        ViewBag.Message = "沒有輸入值";
    }
    catch (OverflowException ex)
    {
        _logger.LogWarning(MyLogEvents.OverflowError, ex, "Path:{path}", Request.Path);
        ViewBag.Message = "超過數值範圍";
    }
    catch (FormatException ex)
    {
        _logger.LogWarning(MyLogEvents.FormatError, ex, "Path:{path}", Request.Path);
        ViewBag.Message = "請輸入數字";
    }
    return View();
}

// home/index.cshtml

<h1>Home</h1>

<form method="post">
    <input type="text" name="number" />
    <input type="submit" value="double" />
</form>
<span>@ViewBag.Message</span>
//=====================
// program.cs
builder.Logging.AddFilter((category, level) => category == "MyLog");
//=====================
// IMyService.cs
public interface IMyService
{
    Guid Id { get; }
}
public class MyService : IMyService
{
    //public Guid Id => Guid.NewGuid();
    public Guid Id { get;  }=Guid.NewGuid();
}

// democontroller.cs
public class DemoController : Controller
{
    public IActionResult Index()
    {
        MyService service = new MyService();
        Console.WriteLine(service.Id);
        Console.WriteLine(service.Id);
        return View();
    }
}
//================================
// DemoController.cs
public class DemoController : Controller
{
    readonly IMyService _myService;

    public DemoController(IMyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        ViewData["id"]=_myService.Id;
        return View();
    }
}

// Demo/index.cshtml
@inject Mod14.IMyService Service
@{
    ViewData["Title"] = "Demo";
}

<h1>Demo</h1>

<ul>
    <li>Controller: @ViewData["id"]</li>
    <li>View: @Service.Id</li>
</ul>

// program.cs
using Mod14;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

//builder.Services.AddTransient<IMyService, MyService>(); 
//builder.Services.AddScoped<IMyService, MyService>();
builder.Services.AddSingleton<IMyService, MyService>();

var app = builder.Build();
app.UseStaticFiles();
app.MapDefaultControllerRoute();

app.Run();

//=====================
// program.cs
//IMyService myService= new MyService();
//Console.WriteLine(myService.Id);
//builder.Services.AddSingleton(myService);

MyService myService = new MyService();
Console.WriteLine(myService.Id);
builder.Services.AddSingleton<IMyService>(myService);
//============================
// imyservice.cs
public class MyService : IMyService, IDisposable
{
    //public Guid Id => Guid.NewGuid();
    public Guid Id { get;  }=Guid.NewGuid();

    public void Dispose()
    {
        Console.WriteLine(nameof(Dispose));
    }
}

// program.cs
//IMyService myService = new MyService();
//Console.WriteLine(myService.Id);
//builder.Services.AddSingleton(myService);

using MyService myService = new MyService();
Console.WriteLine(myService.Id);
builder.Services.AddSingleton<IMyService>(myService);
//=================================
// program.cs
var p1 = builder.Environment.ContentRootFileProvider;
builder.Services.AddSingleton(p1);

// demo2controller.cs
public class Demo2Controller : Controller
{

    readonly IFileProvider _provider;

    public Demo2Controller(IFileProvider provider)
    {
        _provider = provider;
    }

    public IActionResult Index()
    {
        var contents = _provider.GetDirectoryContents("");
        return View(contents);
    }
}

// demo2/index.cshtml
@using Microsoft.Extensions.FileProviders
@model IDirectoryContents
@{
    ViewData["Title"] = "Demo2";
}

<h1>Demo2</h1>

<ul>
    @foreach (var item in Model)
    {
        <li>@item.Name: @item.IsDirectory</li>
    }
</ul>

//=====================================
// demo2controller.cs
public IActionResult Select(string name)
{
    var contents = _provider.GetDirectoryContents("");
    var file = _provider.GetFileInfo(name);
    using var reader = new StreamReader(file.CreateReadStream());
    ViewData["result"] = reader.ReadToEnd();
    return View(nameof(Index), contents);
}

// demo2/index.cshtml
@using Microsoft.Extensions.FileProviders
@model IDirectoryContents
@{
    ViewData["Title"] = "Demo2";
}

<h1>Demo2</h1>

<ul>
    @foreach (var item in Model)
    {
        if (item.IsDirectory)
        {
            <li>@item.Name</li>
        }
        else
        {
            <li><a href="~/demo2/select?name=@item.Name">@item.Name</a></li>
        }
    }
</ul>
<hr />
<pre>
@ViewData["result"]
</pre>
//=====================================
// .csproj
<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="6.0.16" />
  <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.16" />
</ItemGroup>

// program.cs
var p1 = builder.Environment.ContentRootFileProvider;
//builder.Services.AddSingleton(p1);

var p2 = new EmbeddedFileProvider(typeof(Program).Assembly);
builder.Services.AddSingleton<IFileProvider>(p2);

//======================================
// program.cs

var p1 = builder.Environment.ContentRootFileProvider;
//builder.Services.AddSingleton(p1);

var p2 = new EmbeddedFileProvider(typeof(Program).Assembly);
//builder.Services.AddSingleton<IFileProvider>(p2);

var p3=new CompositeFileProvider(p1, p2);
builder.Services.AddSingleton<IFileProvider>(p3);

```