문제 설명
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.Khooryani、rekiem87)