Sunny
Sunny

Reputation: 4809

Can repository class be scoped as singleton in ASP.NET

I am trying to understand the scope of repository class in ASP.NET application. I assume they are thread safe in request scope since each request runs on a seperate thread. But how about having it singleton, is it a valid scenario.

Because these classes doesn't have state but only methods which manipulate data, so different threads executing these methods might be having different stack frames. Is my understanding right, could anyone provide more insights.

interface ICustomerRepository
{
   List<Customers> GetAll();
   Customer GetById(int id);
}

public class Customer : ICustomerRepository
{
   //implement methods

}

Upvotes: 3

Views: 8346

Answers (1)

Wiktor Zychla
Wiktor Zychla

Reputation: 48279

Exposing a repository as a singleton for a concurrent environment is a bad idea.

You could possibly implement interface repository in a way that is safe to be used concurrently but this means that the only guarantee of concurrency consistency lies somewhere in the implementation. There is no other mechanism to enforce that concurrent calls would not fail, the contract at the programming language level (repository interface) is just too weak to express such requirement.

On the other hand, if each http context gets its own instance, the implementation details do not matter.

I suggest you read more on object lifetime. A singleton is just a specific example of a more general idea of controlling the lifetime. You can have objects with transient lifetime, objects that are shared in a single instance for the lifetime of you application but also objects that live in a context of a thread or an http context (that possibly spans multiple threads). And one of ways to control the lifetime is to have a factory that creates instances.

If you need something simple, you could have something that looks like a singleton but controls the lifetime in an arbitrary way:

http://netpl.blogspot.com/2010/12/container-based-pseudosingletons-in.html

Upvotes: 6

Related Questions