我正忙着做一个定制的CMS和网站。CMS和网站都共享相同的数据层,数据层使用的是一个通用存储库模式和一个工作单元存储库。
这个问题发生在我浏览网页时,网页上有一个简单的文本行。这一行文本是在CMS中编辑的。在编辑这一行文本并将其保存到CMS中时,我会看到正在修改的实体,以及数据库中的更改。然而,在通过CMS修改了这一小部分文本,然后刷新了网站页面后,我仍然会看到旧的文本。
要想显示新的、已更改的文本,唯一的方法是重新启动IIS,在web.config中添加一个空间并保存它,以便回收应用程序池。因此,在我看来,这与实体上下文的缓存有关。
下面是我的通用存储库代码和我的工作单元存储代码。我认为问题就在其中之一,在某种程度上,实体上下文的缓存需要更新,或者实体需要重新加载。我能做些什么来解决这个问题呢?
信息:工作单元是基于http://samscode.com/index.php/2009/12/making-entity-framework-v1-work-part-1-datacontext-lifetime-management/的文章。该网站和CMS在本地开发pc上的独立IIS应用程序池中运行。
GenericRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using CORE.Model;
using CORE.RepositoryInterfaces;
namespace CORE.Repositories
{
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
#region Implementation of IRepository<TEntity>
//private readonly myContext _context;
private readonly DbSet<TEntity> _dbSet;
public GenericRepository()
{
//_context = new myContext();
//_dbSet = _context.Set<TEntity>();
_dbSet = DataLayer.Instance.Context.Set<TEntity>();
}
/// <summary>
/// Inserts a new object into the database
/// </summary>
/// <param name="entity">The entity to insert</param>
public void Insert(TEntity entity)
{
_dbSet.Add(entity);
}
/// <summary>
/// Deletes the specified entity from the database
/// </summary>
/// <param name="entity">The object to delete</param>
public void Delete(TEntity entity)
{
if (DataLayer.Instance.Context.Entry(entity).State == System.Data.EntityState.Detached)
{
_dbSet.Attach(entity);
}
_dbSet.Remove(entity);
}
/// <summary>
/// Saves all pending chances to the database
/// </summary>
public void Save()
{
try
{
DataLayer.Instance.Context.SaveChanges();
}
catch (DbEntityValidationException e)
{
//foreach (var eve in e.EntityValidationErrors)
//{
// Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
// eve.Entry.Entity.GetType().Name, eve.Entry.State);
// foreach (var ve in eve.ValidationErrors)
// {
// Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
// ve.PropertyName, ve.ErrorMessage);
// }
//}
//throw;
//Log all errors to an temp file.
//TODO: Implement NLog
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format(
"- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
File.AppendAllLines(@"c:\temp\errors.txt", outputLines);
throw;
}
}
/// <summary>
/// Retrieves the first object matching the specified query.
/// </summary>
/// <param name="where">The where condition to use</param>
/// <returns>The first matching object, null of none found</returns>
public TEntity First(Expression<Func<TEntity, bool>> @where)
{
return _dbSet.FirstOrDefault(where);
}
/// <summary>
/// Gets a list of all objects
/// </summary>
/// <returns>An strong typed list of objects</returns>
public IEnumerable<TEntity> GetAll()
{
return _dbSet.AsEnumerable();
}
/// <summary>
/// Returns ans iQueryable of the matching type
/// </summary>
/// <returns>iQueryable</returns>
public IQueryable<TEntity> AsQueryable()
{
return _dbSet.AsQueryable();
}
//public void Dispose()
//{
// DataLayer.Instance.Context.Dispose();
// GC.SuppressFinalize(this);
//}
#endregion
}
}UnitOfWorkStore.CS
using System.Runtime.Remoting.Messaging;
using System.Web;
namespace CORE
{
/// <summary>
/// Utility class for storing objects pertinent to a unit of work.
/// </summary>
public static class UnitOfWorkStore
{
/// <summary>
/// Retrieve an object from this store via unique key.
/// Will return null if it doesn't exist in the store.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static object GetData(string key)
{
if (HttpContext.Current != null)
return HttpContext.Current.Items[key];
return CallContext.GetData(key);
}
/// <summary>
/// Put an item in this store, by unique key.
/// </summary>
/// <param name="key"></param>
/// <param name="data"></param>
public static void SetData(string key, object data)
{
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = data;
else
CallContext.SetData(key, data);
}
}
}DataLayer.cs
using System;
using CORE.Model;
namespace CORE
{
/// <summary>
/// This is the data access layer management class.
/// See
/// </summary>
public sealed class DataLayer : IDisposable
{
/// <summary>
/// This is our key to store an instance of this class in the <see cref="UnitOfWorkStore" />.
/// This is used in the <see cref="Instance" /> property.
/// </summary>
private const string UowInstanceKey = "MyContext_Instance";
/// <summary>
/// This is used for thread-safety when creating the instance of this class to be stored in
/// the UnitOfWorkStore.
/// </summary>
private static readonly object SObjSync = new object();
// The DataContext object
private readonly MyContext _context;
// ********************************************************************************
// *** Constructor(s) *************************************************************
// ********************************************************************************
/// <summary>
/// Default constructor. Creates a new MyEntities DataContext object.
/// This is hidden (private) because the instance creation is managed as a "unit-of-work", via the
/// <see cref="Instance" /> property.
/// </summary>
private DataLayer()
{
_context = new MyContext();
}
// ********************************************************************************
// *** Public properties **********************************************************
// ********************************************************************************
/// <summary>
/// The ObjectContext object that gives us access to our business entities.
/// Note that this is NOT static.
/// </summary>
public BorloContext Context
{
get { return _context; }
}
/// <summary>
/// This will get the "one-and-only" instance of the DataLayer that exists for the lifetime of the current "unit of work",
/// which might be the lifetime of the currently running console application, a Request/Response iteration of an asp.net web app,
/// an async postback to a web service, etc.
///
/// This will never return null. If an instance hasn't been created yet, accessing this property will create one (thread-safe).
/// This uses the <see cref="UnitOfWorkStore" /> class to store the "one-and-only" instance.
///
/// This is the instance that is used by all of the DAL's partial entity classes, when they need a reference to a MyEntities context
/// (DataLayer.Instance.Context).
/// </summary>
public static DataLayer Instance
{
get
{
object instance = UnitOfWorkStore.GetData(UowInstanceKey);
// Dirty, non-thread safe check
if (instance == null)
{
lock (SObjSync)
{
// Thread-safe check, now that we're locked
// ReSharper disable ConditionIsAlwaysTrueOrFalse
if (instance == null) // Ignore resharper warning that "expression is always true". It's not considering thread-safety.
// ReSharper restore ConditionIsAlwaysTrueOrFalse
{
// Create a new instance of the DataLayer management class, and store it in the UnitOfWorkStore,
// using the string literal key defined in this class.
instance = new DataLayer();
UnitOfWorkStore.SetData(UowInstanceKey, instance);
}
}
}
return (DataLayer)instance;
}
}
public void Dispose()
{
_context.Dispose();
GC.SuppressFinalize(this);
}
}
}更新- 1:通过泛型服务使用GenericRepository
在CMS:服务中的使用
private readonly IGenericService<TextBlock> _textBlockService;
public TextBlockController(): base(new GenericService<ComponentType>(), new GenericService<Blog>())
{
if (_textBlockService == null)
{
_textBlockService = new GenericService<TextBlock>();
}
}服务前端的使用,通过helper
public static class RenderEngine
{
private static readonly IGenericService<Component> ComponentService;
private static readonly IGenericService<TextBlock> TextBlockService;
/// <summary>
/// Constructor for this class.
/// </summary>
static RenderEngine()
{
if (ComponentService == null)
{
ComponentService = new GenericService<Component>();
}
if (TextBlockService == null)
{
TextBlockService = new GenericService<TextBlock>();
}
}
//Html helper method does something like TekstBlokService.First(/*linq statement*/)
}更新- 2:为泛型服务添加的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using CORE.Repositories;
using CORE.RepositoryInterfaces;
using BLL.ServiceInterfaces;
namespace BLL.Services
{
public class GenericService<T> : IGenericService<T> where T : class
{
#region properties
protected readonly IGenericRepository<T> MyRepository;
#endregion
#region constructor
//[Inject]
public GenericService(IGenericRepository<T> repository)
{
MyRepository = repository;
}
//public GenericService()
//{
// if (Repository == null)
// {
// Repository = new Repository<T>();
// }
//}
////todo: uitzoeken!
public GenericService()
: this(new GenericRepository<T>())
{
}
#endregion
#region Implementation of IService<T>
/// <summary>
/// Inserts a new object into the database
/// </summary>
/// <param name="entity">The entity to insert</param>
public void Insert(T entity)
{
MyRepository.Insert(entity);
}
/// <summary>
/// Retrieves the first object matching the specified query.
/// </summary>
/// <param name="where">The where condition to use</param>
/// <returns>The first matching object, null of none found</returns>
public T First(Expression<Func<T, bool>> @where)
{
return MyRepository.First(where);
}
/// <summary>
/// Gets a list of all objects
/// </summary>
/// <returns>An strong typed list of objects</returns>
public IEnumerable<T> GetAll()
{
return MyRepository.GetAll();
}
/// <summary>
/// Returns ans iQueryable of the matching type
/// </summary>
/// <returns>iQueryable</returns>
public IQueryable<T> AsQueryable()
{
return MyRepository.AsQueryable();
}
/// <summary>
/// Deletes the specified entity from the database
/// </summary>
/// <param name="entity">The object to delete</param>
public void Delete(T entity)
{
MyRepository.Delete(entity);
}
/// <summary>
/// Saves all pending chances to the database
/// </summary>
public void Save()
{
MyRepository.Save();
}
//protected override void Dispose(bool disposing)
//{
// _movieService.Dispose();
// base.Dispose(disposing);
//}
#endregion
//public void Dispose()
//{
// MyRepository.Dispose();
// GC.SuppressFinalize(this);
//}
}
}发布于 2013-10-26 16:26:13
问题确实出现了,在这里:
public static class RenderEngine
{
private static readonly IGenericService<Component> ComponentService;
private static readonly IGenericService<TextBlock> TextBlockService;
/// <summary>
/// Constructor for this class.
/// </summary>
static RenderEngine()
{
if (ComponentService == null)
{
ComponentService = new GenericService<Component>();
}
if (TextBlockService == null)
{
TextBlockService = new GenericService<TextBlock>();
}
}
//Html helper method does something like TekstBlokService.First(/*linq statement*/)
}假设GenericService是GenericRepository或持有GenericRepository:
使用一些静态字段来引用您的GenericService实例保持活动的GenericRepository实例,这反过来又保持活动的DBSets包含字段(称为_dbSet)及其相关的DataContexts。
由于GenericRepositories类从instances的构造函数中获取它们的DbSets,并且不再更新它们,相应的“静态实例”将继续使用它们获得的第一个类,并且这些实例将在相关的instances的整个生命周期中持续。
这意味着您的Datacontext及其相关的DbSets实例不会在每次收到新的GenericServices/GenericRepositories请求时被更新,因为它们应该用于静态GenericServices/GenericRepositories。实际上,使用HttpContext.Current.Items来管理DataContext生命周期表明,您想要做的是为每个新的HTTP请求创建一个新的。(这就是你指出的文章的目的)。
让我们来总结一下:
DataContext /GenericRespositories引用的GenericServices实例才会被更新。GenericRepository“静态实例”总是在HTTP请求中使用相同的DbSets和DataContexts,而不是新的请求,这会导致实体刷新问题。GenericRepositories“静态实例”获取旧实体,使用GenericRepositories“新实例”(来自控制器)获取最新数据(因为它们的_dbSet字段填充了由UnitOfWorkStore提供的新的DataContext )。要解决这个问题,有许多解决方案,下面是几个:
DBSet引用保存到GenericRepositories中GenericServices或GenericRepositories用作静态字段/属性希望所有这些假设都有助于朝着正确的方向发展。
发布于 2013-10-26 15:18:12
试试context.Entry(<!-- Name -->).Reload();
https://stackoverflow.com/questions/19607112
复制相似问题