dotnet core-Logging 클래스 라이브러리 (dotnet core-Logging in class library)


문제 설명

dotnet core‑Logging 클래스 라이브러리 (dotnet core‑Logging in class library)

Microsoft.Extensions.Logging 내 ASP.NET Core 웹 응용 프로그램이 해당 라이브러리를 사용하는 클래스 라이브러리에서 컨트롤러(생성자에 넣고 프레임워크는 DI로 처리)에서 로깅을 사용합니까? 클래스를 인스턴스화하고 메서드를 사용하는 방법은 무엇입니까?

public class MyMathCalculator
{
    private readonly ILogger<MyMathCalculator> logger;

    public MyMathCalculator(ILogger<MyMathCalculator> logger)
    {
        this.logger = logger;
    }

    public int Fact(int n)
    {
        //logger.LogInformation($"Fact({n}) called.");
        if (n == 0)
        {
            return 1;
        }
        return Fact(n ‑ 1) * n;
    }
}

참조 솔루션

방법 1:

Taked from a previous answer:

...That is the magic of dependency injection, just let the system create the object for you, you just have to ask for the type.

This is also a big topic, ... basically, all you have to do is to define classes as dependencies, so, when you ask for one, the system itself check the dependencies, and the dependencies of that objects, until resolves all the tree of dependencies.

With this, if you need one more dependency latter in your class, you can add directly but you do not need to modify all the classes that uses that class.

To use this in the controller, please check the official docs, you just have to add you dependencies to the constructor, and win!, basically two parts:

Add in your Startup.class

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}

Then in your controller:

public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }

This sould be no different if you library class is in other project, at the end of the day you will be adding the class to the startup, that is how asp net knows what to load.

If you want your code clean, you can use an Extension method to group all your declarations and the just calling services.AddMyAwesomeLibrary(), for example:

In your awesomeLibraryProject:

public static class MyAwesomeLibraryExtensions
{
    public static void AddMyAwesomeLibrary(this IServiceCollection services)
    {
        services.AddSingleton<SomeSingleton>();
        services.AddTransient<SomeTransientService>();
    }
}

And in your Startup

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddMyAwesomeLibrary();
    }

(by M.Khooryanirekiem87)

참조 문서

  1. dotnet core‑Logging in class library (CC BY‑SA 2.5/3.0/4.0)

#asp.net-core #.net-core #C# #logging






관련 질문

ASP.NET 5 프로젝트용 DNX를 선택하는 방법 (How to choose DNX for ASP.NET 5 project)

ASP.NET 5 - 프로젝트의 파일 참조(csproj와 유사한 참조 누락) (ASP.NET 5 - Referencing files in projects (missing csproj-like references))

ASP.NET 5에 OData를 등록하는 방법 (How to register OData with ASP.NET 5)

Asp.net 5 - 도커 (Asp.net 5 - Docker)

ASP.NET Core MVC에서 컨트롤러별로 데이터베이스에서 정보 읽기 (Reading information from database by controller in ASP.NET Core MVC)

이 목록에 정렬 오류가 있는 이유는 무엇입니까? (Why is there a sorting error in this list?)

foreach 루프에서 모든 데이터를 반환하는 방법 (How to return all data in foreach loop)

읽기 전용 면도기 C# asp.net의 드롭다운 목록을 만드는 방법 (how to make dropdownlistfor readonly razor c# asp.net)

.net Core: C# 코드에서 매개 변수를 전달하고 Azure 데이터 팩터리 파이프라인을 실행하는 방법은 무엇입니까? (.net Core : How to pass parameters and run Azure data factory pipeline from C# Code?)

현재 .NET SDK는 TFS 2015 빌드에서 .NET Core 3.0 대상 지정을 지원하지 않습니다. (The current .NET SDK does not support targeting .NET Core 3.0 on TFS 2015 build)

HTTP 오류 500.30 - ANCM 진행 중인 시작 실패 Asp.net-Core 3.1 (HTTP Error 500.30 - ANCM In-Process Start Failure Asp.net-Core 3.1)

System.Data.SqlClient.TdsParser' 예외가 발생했습니다: System.BadImageFormatException: 잘못된 형식의 프로그램을 로드하려고 했습니다. (System.Data.SqlClient.TdsParser' threw an exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format)







코멘트