Here’s the basic setup. On an ASP.Net website, there are a few pages that display reports from data that comes from a database. All the data comes via stored procedures that is accessed usign Linq to Sql. These pages may have some very high traffic at different times. We’re using ASP.Net with the MVP pattern, and Unity for IoC (although this question is the same regardless of container.) Each Presenter gets injected with an IDataRepository that gets injected with an IDataAccess which news up a Linq to Sql DataContext under the hood.
The question is, when wiring up the container, should we use RegisterInstance (singleton) for the IDataAccess, or should we use RegisterType. I guess the question really comes down to this: How does Unity handle Dispose() (when using RegisterType, will it properly dispose of my DataAccess class that disposes of the DataContext) and how expensive is it to new up a DataContext. On the flip side, what’s the downsize of having (potentially) multiple threads hitting the same DataContext?
One final note, not sure if this is relevant, the DataContext is used strictly to read data in this case, it never does any writes.
In general,
DataContexts are not thread safe. But they are designed to be cheap to setup and teardown, and are lightweight. You should think of them as units of work. Accordingly, you should use one for each “conversation” with the database (only you can decide what a “conversation” is).Therefore, I would strongly encourage you to not set the lifecycle of the
DataContextto be singleton.Further, if you’re using it only to do reads, you should set
ObjectTrackingEnabledto be disabled (similar toIStatelessSessionin NHibernate).