0

If I wish to inject my DbContext into one of my controllers as follows:

public class HomeController : Controller
{
    MyDbContext _db;

    public HomeController(MyDbContext db)
    {
        _db = db;
    }

    ...
}

What is the correct way to configure this with Unity. The context would have to intantiated per request so PerRequestLifetimeManager seems like the natural choice. But from reading this documentation it seems that PerRequestLifetimeManager is advised against. The terms "thread-unsafe dependencies" make me nervous about using it as do the warning about it causing "bugs in the end user’s application code". The warnings seem to be very vague though so that it is not clear what the dangers actually are. Can anyone give examples of the kind of bugs that can occur from the use of PerRequestLifetimeManager? And if this lifetime manager is advised against, what would be a better way to inject the DbContext into my controllers?

BruceHill
  • 6,954
  • 8
  • 62
  • 114
  • I assume a requirement would be that the same context is injected as long as it's the same request. So, let's say if you have a `Controller`and a `Service`, which both injects `MyDbContext`, it would be the same reference in both? – smoksnes Jul 22 '16 at 11:08
  • Yes, that is correct. I want a DbContext that is created at the start of the request, disposed at the end and passed into the controller and any services defined. – BruceHill Jul 22 '16 at 17:33
  • [This answer](http://stackoverflow.com/a/25671643/1370166) might answer some of your questions. – TylerOhlsen Jul 28 '16 at 03:24

0 Answers0