实体类中的依赖注入 [英] Dependency Injection into Entity Class

查看:437
本文介绍了实体类中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Asp.Net Core,我们可以在控制器/存储库中使用依赖注入.

Using Asp.Net Core we can make use of Dependency Injection in controllers/repositories.

但是,我希望在实体类中进行一些记录.

However, I wish do do some logging in my Entity Class.

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类时,它不会尝试注入任何依赖项.

When the Person class is instantiated by EntityFramework it does not attempt to inject any dependencies.

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

Can I force this? Am i going about it in completely the wrong way?

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

Ultimatley I just want to be able to use logging consistently throughout the application.

谢谢

推荐答案

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

It is possible but I don't recommend it because I agree with commenters that logging belongs in your services and controllers.

EF Core 2.1允许将DbContext注入EF将调用的私有构造函数中.请参见官方文档.

EF Core 2.1 allows injecting the DbContext into a private constructor that EF will invoke. See the official docs.

首先,您需要在DbContext类中公开一个LoggerFactory属性.

First you need to expose a LoggerFactory property in your DbContext class.

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options, ILoggerFactory loggerFactory = null)
    {
        LoggerFactory = loggerFactory;
    }

    public ILoggerFactory LoggerFactory { get; }
}

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

Then you can inject the DbContext into a private constructor in your entity class.

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

这篇关于实体类中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆