[英]Dependency Injection into Entity Class
使用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;
}
}
當Person類由EntityFramework實例化時,它不會嘗試注入任何依賴項。
我可以強迫這個嗎? 我是以完全錯誤的方式進行的嗎?
Ultimatley我只是希望能夠在整個應用程序中始終如一地使用日志記錄。
謝謝,
這是可能的,但我不推薦它,因為我同意評論者記錄屬於您的服務和控制器。
EF Core 2.1允許將DbContext注入到EF將調用的私有構造函數中。 查看官方文檔 。
首先,您需要在DbContext類中公開LoggerFactory
屬性。
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options, ILoggerFactory loggerFactory = null)
{
LoggerFactory = loggerFactory;
}
public ILoggerFactory LoggerFactory { get; }
}
然后,您可以將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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.