实体类中的依赖注入

时间:2018-06-28 12:20:11

标签: c# entity-framework logging asp.net-core dependency-injection

使用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;
    }
}

当EntityFramework实例化Person类时,它不会尝试注入任何依赖项。

我可以强制吗?我会以完全错误的方式进行操作吗?

Ultimatley我只希望能够在整个应用程序中始终使用日志记录。

谢谢

1 个答案:

答案 0 :(得分:4)

有可能,但我不建议这样做,因为我同意评论者的观点,日志记录属于您的服务和控制器。

EF Core 2.1允许将DbContext注入EF将调用的私有构造函数中。参见official docs

首先,您需要在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; } } 属性。

any

然后,您可以将DbContext注入实体类中的私有构造函数中。

s1