JNB
JNB

Reputation: 428

Dependency Injection into Entity Class

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

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 I just want to be able to use logging consistently throughout the application.

Thanks,

Upvotes: 8

Views: 7241

Answers (1)

Brad
Brad

Reputation: 4553

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 allows injecting the DbContext into a private constructor that EF will invoke. See the official docs.

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

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

Upvotes: 7

Related Questions