views:

36

answers:

2

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.

+1  A: 

There is a difference between Singleton Pattern and Singleton Scope and Most of the DI frameworks including UNITY use Singleton Scope.

Singleton Scope : Only one instance exist per injector and this is very important concept because in a application there may be more than one injector coexist so more than one singleton, In this case each injector will hold a different instance of the singleton scoped object.Most of us includig me beleives that singleton means one instance for the life of an application but in DI it is not the case.

There is a very good book on Dependecy Injection by Dhanji R. Prasanna.

saurabh
I had no idea, I thought it was a true singleton, thanks for the info!
BFree
+3  A: 

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 DataContext to be singleton.

Further, if you're using it only to do reads, you should set ObjectTrackingEnabled to be disabled (similar to IStatelessSession in NHibernate).

Jason
Exactly what I needed to know. Thanks.
BFree