Jam*_*s B 8 c# logging entity-framework dependency-injection asp.net-core
使用 Asp.Net Core,我们可以在控制器/存储库中使用依赖注入。
但是,我希望在我的实体类中做一些日志记录。
class Person
{
private ILogger<Person> _logger;
private List<Pets> pets;
public Person(ILogger<Person> logger)
{
_logger = logger;
}
public bool HasCat()
{
_logger.LogTrace("Checking to see if person has a cat.");
// logic to determine cat ownership
hasCat = true;
return hasCat;
}
}
Run Code Online (Sandbox Code Playgroud)
当 EntityFramework 实例化 Person 类时,它不会尝试注入任何依赖项。
我可以强迫这个吗?我是否以完全错误的方式进行处理?
最后,我只想能够在整个应用程序中一致地使用日志记录。
谢谢,
这是可能的,但我不推荐它,因为我同意评论者的意见,即日志记录属于您的服务和控制器。
EF Core 2.1 允许将 DbContext 注入到 EF 将调用的私有构造函数中。请参阅官方文档。
首先,您需要LoggerFactory在 DbContext 类中公开一个属性。
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options, ILoggerFactory loggerFactory = null)
{
LoggerFactory = loggerFactory;
}
public ILoggerFactory LoggerFactory { get; }
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将 DbContext 注入实体类中的私有构造函数。
public class Person
{
private readonly ILogger _logger;
public Person() { } // normal public constructor
private Person(MyDbContext db) // private constructor that EF will invoke
{
_logger = db.LoggerFactory?.CreateLogger<Person>();
}
public bool HasCat()
{
_logger?.LogTrace("Check has cat");
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3242 次 |
| 最近记录: |