1

I have an MVC application, which also uses EF and a simple Unit of work pattern implementation. Here's what my UnitOfWork looks like:

public class UnitOfWork : IUnitOfWork
{
    [ThreadStatic]
    private static UnitOfWork _current;

    private MyContext _context;

    public static UnitOfWork Current
    {
        get { return _current; }
    }

    public UnitOfWork()
    {
         _current = this;
    }

    public MyContext GetContext()
    {
        if(_context == null)
            _context = new MyContext();

        return _context;
    }

    public int Commit()
    {
        return _context == null ? 0 : _context.SaveChanges();
    }

    public void Dispose()
    {
        _current = null;

        if(_context != null)
            _context.Dispose();
    }
}

I have a generic repository which encapsulates common db operations:

public class GenericRepository<TEntity, TEntityKey> where TEntity : class
{
    private MyContext _context;

    private MyContext Context
    {
        get { return _context ?? (_context = UnitOfWork.Current.GetContext()); }
    }

    public void Add(TEntity newEntity)
    {
       _context.Set<TEntity>().Add(newEntity);
    }

    //Other methods...
}

How it is used:

using(var unitOfWork = _unitOfWorkFactory.Create())
{
    _repository.Add(newEntity);
    unitOfWork.Commit();
}

So, the question is if it is possible, that the MVC framework internally switches threads while processing a request. Since the current UnitOfWork is thread static, such a switch will cause a NullReferenceException when calling UnitOfWork.Current (please correct if I'm not right).

John Saunders
  • 160,644
  • 26
  • 247
  • 397
nativehr
  • 1,131
  • 6
  • 16
  • I would imagine that each request to a controller method gets a single thread with which it fulfills the entire request, unless you do something like `ThreadPool`, `Task` or `async`. What does `MyContext` do? – Robert Harvey Jan 11 '14 at 20:36
  • You should fix your code in 4th line of `UnitOfWOrk` – Grzegorz W Jan 11 '14 at 20:38
  • `MyContext` represents the db, it is a simple class derived from EF's `DbContext`. – nativehr Jan 11 '14 at 20:42
  • 1
    ASP.NET _loves_ thread-switching, yummy sneaky sudden thread-switching. Specially if you build async stuff. How about using HttpContext.Items instead? – sisve Jan 11 '14 at 20:45
  • It has just `DbSet`'s of the entities. I don't have any parallel code (and this code works as well), I meant exactly "internal" switches. – nativehr Jan 11 '14 at 20:48
  • Simon, thank you! Will consider this. – nativehr Jan 11 '14 at 20:50
  • If Microsoft does not guarantee not to switch threads, then you should assume that threads are switched whenever Microsoft feels like it. And what about third party code (HttpModule, etc)? – John Saunders Jan 11 '14 at 21:06
  • John, thanks, I see I should not rely on `ThreadStatic` – nativehr Jan 11 '14 at 21:12

0 Answers0