Dependency Injection into Entity Class

前端 未结 1 1273
臣服心动
臣服心动 2021-01-12 17:56

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          


        
1条回答
  •  清酒与你
    2021-01-12 18:09

    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 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();
        }
    
        public bool HasCat()
        {
            _logger?.LogTrace("Check has cat");
            return true;
        }
    }
    

    0 讨论(0)
提交回复
热议问题