如何在 .net 核心中的控制器的新 class 对象中提供 ILogger<ClassName> 实例?

How to provide ILogger<ClassName> instance in new class object from controller in .net core?

As giving null it gives Value cannot be null. (Parameter 'logger') error. Even if instance of model is given it still stays null

 public class MyController : Controller
    {
            public MyController(ILogger<MyController> logger)
            {
              logger.LogInformation("Log Testing");
            }

            public ActionResult List()
            {
                int Id = 5;
                MyModel model = new MyModel(null);
                model.GetItem(Id);
                return View("List", model);
            }
    }

public class MyModal:BaseModel
{
    private readonly ILogger<MyModal> _logger;
    public MyModel(ILogger<MyModel> logger) 
        {
           this._logger = logger;
        }

    public MyModel GetItem (Int Id)
    {
      try
      {
        //My Code
      }
      catch(Exception e){
       _logger.LogError(e.Message);
      }
    }
}

根据建议我编辑了我的问题

如评论中所建议:

  1. ILoggerFactory注入MyController并将其存储在字段变量中(例如_loggerFactory)。
  2. 在您的 List 方法中使用工厂为 MyModel 构造记录器:ILogger<MyModel> modelLogger = _loggerFactory.CreateLogger<MyModel>();
  3. 将其传递给MyModel构造函数:MyModel model = new MyModel(modelLogger);

示例:

public class MyController
{
    private readonly ILogger _logger;
    private readonly ILoggerFactory _loggerFactory;
    
    public MyController(ILogger<MyController> logger, ILoggerFactory loggerFactory)
    {
        _logger = logger;
        _loggerFactory = loggerFactory;
    }

    public ActionResult List()
    {
        int Id = 5;
        ILogger<MyModel> modelLogger = _loggerFactory.CreateLogger<MyModel>();
        MyModel model = new MyModel(modelLogger);
        model.GetItem(Id);
        return View("List", model);
    }
}

Try it online