1

I'm experiencing some problem with the context using EF5. I'm still studying the problem, but I was thinking is would be a good idea to implement my DataContext class with the singleton pattern, in order to have the same object used by different entity repository. Is a suicide or does it make sense? Another idea is implement a ContextManager like here: http://www.codeproject.com/Articles/70061/Architecture-Guide-ASP-NET-MVC-Framework-N-tier-En (but I'm still checking his code and I don't really understand it in depth yet).

What do you think?

--EDIT--

In a web application, I'm implementing a repository for each entity I have to manage

public DataContext : DbContext
{
    //...
}

Solution 1: fine, but if I would need to make several actions in one call, i.e. an insert and a delete, I'll make two calls to db, I think.

public Entity1Repository
{
    public void Add(Entity1 entity)
    {
        using(DataContext context = new DataContext())
        {
            context.Entity1.Add(entity);
            context.SaveChanges();
        }
    }
    public void Delete(Entity1 entity)
    {
        using(DataContext context = new DataContext())
        {
            context.Entity1.Remove(entity);
            context.SaveChanges();
        }
    }
}

Solution 2: in this case I think I'll have just one call to db, but I need to remember to call the Dispose()

public Entity1Repository
{
    private DataContext context;

    public void Add(Entity1 entity)
    {
        context.Entity1.Add(entity);
    }

    public void Save() 
    {
        context.SaveChanges();
    }

    public void Dispose()
    {
        context.Dispose();
    }
}

Which is the best implementation? (If I understood correctly, singleton is not a good one)

Davide
  • 1,065
  • 3
  • 15
  • 34
  • 1
    It depends on the type of application you are trying to build - [this](http://stackoverflow.com/questions/3653009/entity-framework-and-connection-pooling/3653392#3653392) can explain you why sharing context is not a good idea. – Ladislav Mrnka Jan 28 '13 at 09:21
  • Thanks, I updated my question with some code and more infos. It seems that the singleton is not a good idea. – Davide Jan 28 '13 at 21:30

1 Answers1

0

I would recommend that you share your dbcontext via constructor injection(Dependency Injection).

I would then use a IoC to inject the context into the container with lifetime per request. So then the dbcontext is created for each request in your web and shared with each repository during that request and then disposed after the request.

Mark seemann has a great book about dependency injection and examples. http://www.manning.com/seemann/

Hopes this helps you getting started.

Jakob
  • 476
  • 4
  • 16