Secondary Db Context in ASP.NET CORE EF
<p>I have a service that sends notifications, it requires a db connection to lookup subscriptions. I also have a controller (and may more) that does some logic, and sends notifications. </p>

<p>The problem with this is, because of <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow">DI</a> it uses the same instance of the <code>DbContext</code> so I get a error thrown for re-using a <code>DataReader</code> in the same context (understandable). </p>

<p>I would really love to do this without enabling the MARS flag in <code>DbConnectionString</code>. Given that the controllers cannot use <code>.ToList()</code> or no tracking and the 'inner' <code>NotificationService</code> needs to lookup the database - is this even possible? </p>

<pre><code>public class NotificationSystem
{
     private readonly DbContext context;
     public NotificationSystem(DbContext context) { this.context = context;}

     public void SendNotification(string username){
       var subscriptions = context.subscriptions.where(u =&gt; u.username == username); 
       // Do some notification stuff
     } 
}
</code></pre>

<p>And a simple controller</p>

<pre><code>public class SendRemindersController : Controller
{
    private readonly DbContext _context;
    private readonly NotificationSystem _notificationSystem;

    public SendRemindersController(DbContext context, NotificationSystem notificationSystem)
    {
        this._context = context;
        this._notificationSystem = notificationSystem;
    }

    [HttpGet]
    public async Task&lt;IActionResult&gt; Get()
    {
        var reminders = _context.Reminders.Where(r =&gt; r.Sent == false &amp;&amp; r.RemindAt &lt; DateTime.UtcNow);

        foreach (var reminder in reminders)
        {
            await _notificationSystem.SendNotificationToUser(reminder.UserId);
            reminder.Sent = true;
        }

        await _context.SaveChangesAsync();
        return Ok();
    }
}
</code></pre>

<p>And <code>startup.cs</code> (yes I know I haven't used an interface, that will get refactored later). </p>

<pre><code>services.AddDbContext&lt;DbContext&gt;(options =&gt; options.UseSqlServer(connection));
services.AddTransient&lt;NotificationSystem, NotificationSystem&gt;();
</code></pre>

<h2>Update</h2>

<p>This question is flawed since i was under the false impression that .ToList/.ToArray also detached the entities from the context. In-fact these do not detach and only execute the query. </p>