2

I'm building a layered application using Entity Framework code first approach with an mvc4 web application, separated mainly in Data, Services, and Web.

From my web I do this:

public void Foo() {
    EntityService _svc = new EntityService();
    Entity = _svc.FindById(1);
}

The service method looks like this:

private readonly MyContext _ctx = new MyContext();

public Entity FindById(long id) {
    return _ctx.Entities.SingleOrDefault(q => q.EntityId == id);
}

The problem is when I need to use more than one service because each service will create it's own context.

Trying to solve this I did something like this:

public class MyContext : DbContext {
    private static MyContext _ctx;

    public MyContext() : base("name=myConnectionString") { }

    public static MyContext GetSharedInstance() {
        return GetSharedInstance(false);
    }

    public static MyContext GetSharedInstance(bool renew) {
        if(_ctx == null || renew)
            _ctx = new MyContext();

        return _ctx;
    }
}

Changed my services as follows:

public class EntityService
{
    private readonly MyContext _ctx;

    public bool SharedContext { get; private set; }

    public EntityService()
        : this(false) { }

    public EntityService(bool sharedContext)
        : this(sharedContext, false) { }

    public EntityService(bool sharedContext, bool renew)
    {
        SharedContext = sharedContext;

        if (SharedContext)
            _ctx = MyContext.GetInstance(renew);
        else
            _ctx = new MyContext();
    }
}

Now if I want to share an instance of my context, I'd do something like this:

EntityService _entitySvc = new EntityService(true, true);
AnotherEntityService _anotherEntitySvc = new AnotherEntityService(true);

Is this, at least, a decent way to overcome this? I'll appreciate any help provided. Thanks.

2 Answers 2

11

Never ever ever ever ever ever ever ever... ever... did I mention ever? I mean it. Never ever create a static data context. Never ever. Really. Can I stress this any more? Never. Don't even think about it. Thinking about it will give you brain cancer.

This is one of the situations in which Dependency injection really shines. With Dependency injection, you can manage the lifetime of your data contexts and make them live for the lifetime of the request, rather than the lifetime of the app pool, as a static does.

To elaborate on why a shared context is bad. Not only is the context shared among your classes, but also among threads and requests. That means two users using the site at the same time will stomp all over each others data context, causing all kinds of problems. Data contexts are NOT thread safe, and they're not concurrent safe.

If you want to share your data context with multiple objects, then you need to pass it in to those objects, either as part of a method call, or as a constructor argument.

I highly recommend doing this via Dependency Injection, however.

7
  • Okay, point taken. Could you please provide me some guidance on how can I accomplish this via DI, maybe a short example which I could use to change it on my solution? Thank you.
    – Esteban
    Sep 14, 2012 at 18:34
  • @Esteban - unfortunately, there a many different kinds of Dependency Injection containers, and you will need to learn more about DI before you even get that far. So it's hard to give a single example, because which DI Container you choose affects things. Sep 14, 2012 at 18:40
  • 1
    @Esteban - you might try this article, it may help mikesdotnetting.com/Article/117/… Sep 14, 2012 at 18:41
  • @MystereMan: I'm aware of DI and I've used it with Unity a while ago, never dive into it anyway. How about injecting the context in the service constructor?
    – Esteban
    Sep 14, 2012 at 18:49
  • 1
    @Esteban - yes, it can be done without DI. Which is why I said I highly recommend doing it with DI. If you're not going to use DI, then instantiate the context in your controller and pass it to your service instance via constructor. Sep 14, 2012 at 18:58
2

I stumbled on this looking for something else, and I recently built a repository pattern for Entity Framework. It's designed to encapsulate the framework, while letting its own repository pattern shine through. You're going to want to follow Mystere Man's advice. Here's a rough sample of how I suggest you approach it.

public class MyContext: DbContext, IUnitOfWork
{
    public IDbSet<Note> Notes { get; set; }
    public IDbSet<DomainType> DomainTypes { get; set; }
    public IDbSet<DomainValue> DomainValues { get; set; }
    public IDbSet<Party> Parties { get; set; }

    public MyContext() :base()
    {
        Configuration.LazyLoadingEnabled = false;
        Configuration.ProxyCreationEnabled = false;
    }
}

As you can see, the DbContext is an IUnitOfWork, which simply has the SaveChanges method on it. This is what you'd pass into your repositories.

public abstract class BaseEfRepository<T, TU> : IRepository<T>
    where T : class 
    where TU : IUnitOfWork
{
    ...
    virtual public T GetSingle(Expression<Func<T, bool>> whereCondition)
    {
        Log.DebugFormat("Called GetSingle<{0}>()...", typeof(T));
        return MyEntitySet.Where(whereCondition).FirstOrDefault();
    } [etc...]

}

This will have most of your basic repository-style collection accessors and anything you want to encapsulate. The UnitOfWork is passed into the repository, so you can have as many repositories as you want on the same transaction.

public class NoteRepository: BaseEfRepository<Note, MyContext>
{
    public NoteRepository(MyContext uow) : base(uow)
    {
        MyEntitySet = uow.Notes;
    }
    public Note GetSingleWithParties(Expression<Func<Note, bool>> whereCondition)
    {
        return [... whatever ...]
    }

}

I hope this proves useful.

2
  • I don't understand from this definition public class NoteRepository: BaseEfRepository<Note, MyContext> where is the MyContext is coming from Jun 5, 2020 at 17:14
  • I'm sorry for taking so long to respond @GiovanniRivas! I haven't been logged in for a long time. "MyContext" is the DbContext of the database, which implements IUnitOfWork. This is the unit of work that can be passed around to have repositories share a transaction. Dec 18, 2020 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.