title: Injecting DbContext and ILogger into database DAL constructor, best practice
body: <p>I am building a Web API in ASP.NET Core 3.1 with Entity Framework.</p>
  
  <p>My database context is registered as a service in the Startup.cs:</p>
  
  <pre><code>services.AddDbContext&lt;LocalDbContext&gt;(options =&gt;
  {
      options.UseSqlServer(builderLocal.ConnectionString);
  });
  </code></pre>
  
  <p>And I am retrieving the <code>DbContext</code> in my controller using DI, passing it into my database-access-class (DAL) when I instantiate it for each method</p>
  
  <pre><code>private readonly LocalDbContext _context;
  
  public HomeController(LocalDbContext context)
  {
      _context = context;
  }
  
  public IActionResult GetSomeData(int id)
  {
      var localDb = new LocalDb(_context);
      return Ok(localDb.GetSomeDataById(id));
  }
  </code></pre>
  
  <p>And then my Database file:</p>
  
  <pre><code>public class LocalDbContext : DbContext
  {
      public LocalDbContext(DbContextOptions&lt;LocalDbContext&gt; options)
          : base (options) { }
  
      **DbSets for my models**
  }
  
  public class LocalDb
  {
      private readonly LocalDbContext _context;
      private readonly ILogger&lt;LocalDb&gt; _logger;
  
      // I would want to avoid having to pass in logger in this contstructor
      public LocalDb(LocalDbContext context) 
      {
          _context = context;
          // Can I retrieve a logger from somewhere else? From the context?
          // _logger = logger; 
      }
  
      public void AddStudent(Student student)
      {
          _context.Student.Add(student);
          try
          {
            _context.SaveChanges();  
          } 
          catch (Exception ex)
          {
              _logger.LogError("logMessage about exception: " + ex.StackTrace);
              throw;
          }
      }
  }
  </code></pre>
  
  <p>So I wish to have the _logger available to write to, but in my code I have not set the _logger to anything. I know <code>ILogger</code> exists in the DbContext, and there is lots of guides explaining how to add and configure the logger for the Context and EF. But when I want to use my <code>LocalDb</code> class, do I have to pass in a ILogger instance for every time i call <code>var localDb = new LocalDb(_context, _logger)</code></p>
  
  <p>I feel like having to pass in a logger instance every time is a bit strange, there must be a better solution to this. Would it be possible to add the LocalDb class as a service, then dependency inject context and logger into that class? Whats the best practice?</p>