ASP.Net 5登录类库 [英] ASP.Net 5 Logging in Class Libraries

查看:50
本文介绍了ASP.Net 5登录类库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对依赖注入有点陌生.我正在尝试开始使用ASP.NET 5,并且正在努力找出如何在ASP.NET 5类库中使用服务.尤其是诸如日志记录和EF数据访问之类的简单事情.

I am a little new to dependency injection. I'm trying to get started with ASP.NET 5 and am struggling to figure out how to use services in my ASP.NET 5 class libraries. Especially the simple things like logging and EF data access.

例如,我在这里遵循了指南: http://docs.asp.net/en/latest/fundamentals/logging.html

For example I have followed the guide here: http://docs.asp.net/en/latest/fundamentals/logging.html

这使我能够登录主应用程序.然后如何在类库中输出日志事件?

This has enabled me to have logging in the main application. How do I then output log events in my class library?

我知道从类库中引用主应用程序是一种不好的做法,并且想弄清楚如何正确地进行操作.

I'm aware that it is bad practice to reference the main application from the class library and wanted to figure out how to do it correctly.

推荐答案

通过在构造函数中传递 ILogger< YourClass> 来为您的课程创建记录器,就像在示例中一样:

Create a logger for your class by passing an ILogger<YourClass> in the constructor exactly like in the sample:

public class MyClass : IMyClass
{
     private readonly ILogger<MyClass> _logger;

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

    public void MyMethod()
    {
        _logger.LogInformation("a log");
    }
}

或传递 ILoggerFactory :

public class MyClass: IMyClass
{
     private readonly ILogger _logger;

     public (ILoggerFactory loggerFactory)
     {
        _logger = loggerFactory.CreatLogger("MyClass");
      }

    public void MyMethod()
    {
        _logger.LogInformation("a log");
    }
}

并通过依赖项注入来解决您的班级:

And resolve your class by Dependency Injection:

services.AddTransient<IMyClass, MyClass>();

然后您可以在控制器中使用它:

Then you can use it in your controller:

[Route("api/[controller]")]
public class TodoController : Controller
{
    private readonly IMyClass _myClass;
    private readonly ILogger<TodoController> _logger;

    public TodoController(IMyClass myClass, 
        ILogger<TodoController> logger)
    {
        _myClass = myClass;
        _logger = logger;
    }
}

这篇关于ASP.Net 5登录类库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆