问题
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).
来源:https://stackoverflow.com/questions/21067521/is-thread-switching-possible-during-request-processing