【发布时间】:2020-11-04 08:55:58
【问题描述】:
我是 .Net Core(使用 3.1)并使用依赖注入的新手。我能够在 Web API 控制器中设置 NLog,但现在我正试图让 NLog 按照我在 API 控制器中所做的基本操作在单独的业务类中工作。我不断收到有关记录器为 NULL 的错误,当我在 _logger 和 _config 上设置断点时,果然它们为 NULL。我不确定我在这里缺少什么。
这是我的商务舱,我认为我的设置正确,但显然没有。
public class ShiftBLL
{
private static IConfiguration _config;
private static ILogger<ShiftBLL> _logger;
public ShiftBLL(ILogger<ShiftBLL> logger, IConfiguration config)
{
_config = config;
_logger = logger;
}
public static List<AppsShift> GetShifts(string station, string shiftDate)
{
_logger.LogInformation("Staion: {0} | ShiftDate: {1}", station, shiftDate);
*code removed for clarity. The app breaks on the initial call of _logger.
}
}
修复
我从 ShiftBLL 类以及本地参数中删除了“静态”。然后我必须在我的控制器中创建一个 ShiftBLL 对象,并从控制器中传入记录器和配置,在控制器中我有 DI 在 ShiftBLL 中工作。我最终在我的控制器中得到了这个:
ShiftBLL BLL = new ShiftBLL(_logger, _config);
listShifts = BLL.GetShifts(station, shiftDate);
这是我更新的 ShiftBLL:
public class ShiftBLL
{
private IConfiguration _config;
private readonly ILogger _logger;
public ShiftBLL(ILogger logger, IConfiguration config)
{
_config = config;
_logger = logger;
}
public List<AppsShift> GetShifts(string station, string shiftDate)
{
_logger.LogInformation("Staion: {0} | ShiftDate: {1}", station, shiftDate);
}
我仍然对依赖注入感到头疼。
【问题讨论】:
-
您可以尝试从类字段中删除“静态”关键字吗?它们在设计上不应该是静态的。编辑:我刚刚注意到,即使 GetShifts 也是静态的,它是从课堂外调用的吗?你能分享一下 GetiShifts 是如何被调用的代码吗?
-
所以我从类中删除了静态并创建了一个 ShiftBLL 的对象。看起来这可能奏效了。我本可以发誓我今天早些时候尝试过,它没有用,但看起来知道。这是我在 Controller 中创建的...ShiftBLL BLL = new ShiftBLL(_logger, _config);
-
像这样声明‘私有只读 ILogger
_logger;’ -
能否分享一下关于如何注册Nlog的程序代码或startup.cs代码?
-
@BrandoZhang 这是我用的:github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3
标签: c# asp.net-core .net-core dependency-injection nlog