<t>NOTE: This answer talks about the Entity Framework's DbContext, but<br/>
it is applicable to any sort of Unit of Work implementation, such as<br/>
LINQ to SQL's DataContext, and NHibernate's ISession.<br/>
<br/>
Let's start by echoing Ian: Having a single DbContext for the whole application is a Bad Idea. The only situation where this makes sense is when you have a single-threaded application and a database that is solely used by that single application instance. The DbContext caches data, and it gets stale pretty soon. This will get you in all sorts of trouble when multiple users or application instances work on that database through the use of the DbContext (which is very common of course).<br/>
<br/>
But I expect you already know that and just want to know why not to just inject a new instance (i.e. with a transient lifestyle) of the DbContext into anyone who needs it. (for more information about why a single DbContext -or even on context per thread- is bad, read this answer).<br/>
<br/>
Let me start by saying that registering a DbContext as transient could work, but typically you want to have a single instance of such a unit of work within a certain scope. In a web application, it can be practical to define such a scope on the boundaries of a web request; thus a Per-Web-Request lifestyle. This allows you to let a whole set of objects operate within the same context. In other words, they operate within the same business transaction.<br/>
<br/>
If you have no goal of having a set of operations operate inside the same context, in that case the transient lifestyle is fine, but there are a few things to consider:<br/>
<br/>
- As every object gets its own instance, every class that changes the state of the system, needs to call
_context.SaveChanges(). Otherwise changes would get lost, because every DbContext instance has its own set of changes. This can complicate your code, and adds a second responsibility to the code (the responsibility of controlling the <br/>
<br/>
(Réponse tronquée)</t>