【问题标题】:dotnet core-Logging in class librarydotnet core-类库中的日志记录
【发布时间】:2019-05-31 14:08:59
【问题描述】:

是否可以在我的 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;
    }
}

【问题讨论】:

  • 当然,为什么不呢?
  • 是的,你可以,你试过什么?
  • @rekiem87 更新问题,我的问题是如何实例化类。

标签: c# asp.net-core logging .net-core


【解决方案1】:

取自previous answer

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

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

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

要在控制器中使用它,请check the official docs,您只需将依赖项添加到构造函数中,然后赢!,基本上是两个部分:

添加到你的 Startup.class

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

然后在你的控制器中:

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();
    }

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

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

在您的 awesomeLibraryProject 中:

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

在你的启动中

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

【讨论】:

  • 呼,是的,只是一个错字
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多