dotnet core-类库中的日志记录

M.K*_*ani 1 c# logging .net-core asp.net-core

是否可以在我的 ASP.NET Core Web 应用程序使用该库的类库中使用Microsoft.Extensions.Logging就像使用登录控制器(放入构造函数和框架使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

rek*_*m87 5

取自之前的回答

...这就是依赖注入的神奇之处,让系统为你创建对象,你只需要询问类型。

这也是一个很大的话题,...基本上,您要做的就是将类定义为依赖项,因此,当您要求时,系统本身会检查依赖项以及该对象的依赖项,直到解决所有问题依赖树。

有了这个,如果你在你的类中需要更多的依赖,你可以直接添加,但你不需要修改所有使用该类的类。

要在控制器中使用它,请查看官方文档,您只需将依赖项添加到构造函数中,然后赢!,基本上是两部分:

添加你的 Startup.class

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后在您的控制器中:

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();
    }
Run Code Online (Sandbox Code Playgroud)

如果您的库类在其他项目中,这应该没有什么不同,在一天结束时,您将将该类添加到启动中,这就是 asp net 知道要加载什么的方式。

如果你想让你的代码干净,你可以使用 Extension 方法来分组你的所有声明和刚刚调用的 services.AddMyAwesomeLibrary(),例如:

在您的 awesomeLibraryProject 中:

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

在你的初创公司

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddMyAwesomeLibrary();
    }
Run Code Online (Sandbox Code Playgroud)