我目前有一个使用Entity Framework 4.1登录数据库的项目,因此我们可以跟踪部署在多个Web服务器上的Web应用程序。我使用Scott Gu's Code First解决方案构建了它。
所以,我有这样的代码:
logging.Logs.Add(newLog);
有时会抛出此错误:
System.NullReferenceException:对象引用未设置为 对象的实例。在 System.Data.Objects.ObjectStateManager.DetectConflicts(IList
1 entries) at System.Data.Objects.ObjectStateManager.DetectChanges() at System.Data.Entity.Internal.Linq.InternalSet
1.ActOnSet(Action action, EntityState newState,Object entity,String methodName)at System.Data.Entity.Internal.Linq.InternalSet1.Add(Object entity) at System.Data.Entity.DbSet
1.Add(TEntity entity)
大部分时间它工作正常,但它会偶尔出现打嗝。当我有多个使用此代码访问/写入同一数据库的服务器时,我是否应该注意最佳实践?
现在使用的方法是每个请求都会导致系统将几个新的日志对象添加到集合中,然后保存它们的分组,而不是保存每个单独的日志记录。这是我班上的概要。
public class LoggingService : ILoggingService
{
Logging.Model.MyLogging logging;
public LoggingService()
{
InitializeLog();
}
/// <summary>
/// Save any pending log changes (only necessary if using the Add methods)
/// </summary>
public void SaveChanges()
{
//ensure that logging is not null
InitializeLog();
logging.SaveChanges();
}
#region Private Methods
private void InitializeLog()
{
if (logging == null)
logging = new Model.MyLogging();
}
private void Log(Level level, int sourceId, string message, bool save, int? siteId = null, int? epayCustomerId = null,
string sessionId = null, int? eventId = null, Exception exception = null)
{
if (sourceId == 0)
throw new ArgumentNullException("sourceId", "The Source Id cannot be null and must be valid.");
var source = (from s in logging.Sources
where s.SourceId == sourceId
select s).FirstOrDefault();
if (source == null)
throw new ArgumentNullException("sourceId", String.Format("No valid source found with Id [{0}].", sourceId));
if (eventId.HasValue)
{
if (eventId.Value > 0)
{
var code = (from e in logging.Events
where e.EventId == eventId.Value
select e).FirstOrDefault();
//if event id was passed in but no event exists, create a "blank" event
if (code == null)
{
Event newCode = new Event()
{
EventId = eventId.Value,
Description = "Code definition not specified."
};
InitializeLog();
logging.Events.Add(newCode);
logging.SaveChanges();
}
}
}
var newLog = new Log()
{
Created = DateTime.Now,
Message = message,
Source = source,
Level = level,
EventId = eventId,
SessionId = sessionId,
SiteId = siteId,
MachineName = System.Environment.MachineName,
};
if (exception != null)
newLog.Exception = String.Format("{0}{1}{2}{1}", exception.Message, Environment.NewLine, exception.StackTrace);
//ensure that the logging is not null
InitializeLog();
logging.Logs.Add(newLog);
if (save)
{
logging.SaveChanges();
}
}
#endregion
}
我在结构图中使用IoC,并没有将此类初始化为单例。
For<ILoggingService>().Use<LoggingService>();
我的上下文类看起来像这样:
internal class MyLogging : DbContext
{
public DbSet<Source> Sources { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<Log> Logs { get; set; }
/// <summary>
/// DO NOT ADD ITEMS TO THIS COLLECTION
/// </summary>
public DbSet<LogArchive> LogArchives { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MyDbContextInitializer());
modelBuilder.Entity<Event>().Property(p => p.EventId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<Source>().Property(p => p.SourceId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<LogArchive>().Property(p => p.LogId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
base.OnModelCreating(modelBuilder);
}
//public class MyDbContextInitializer : DropCreateDatabaseIfModelChanges<MyLogging>
public class MyDbContextInitializer : CreateDatabaseIfNotExists<MyLogging>
{
protected override void Seed(MyLogging dbContext)
{
// seed data
base.Seed(dbContext);
}
}
}
我可能做了一些明显错误的事情,但我只是没有看到它。
修改 根据要求,以下是我如何调用日志服务代码的示例。此特定方法是记录与HTTP请求相关的信息。我将日志项追加到一个try catch并保存在一个单独的try catch中,这样如果出现问题,它至少会保存所添加的内容。处理程序是通过IoC注入此类的另一个服务,它通过电子邮件将错误的详细信息发送给我。
服务器的单个帖子可以记录多达50-70个单独的详细信息,分成10-15个块(http请求,发送到Web服务的数据,Web服务调用的结果,响应客户端的响应)这就是为什么我想添加一个分组然后保存分组,而不是打开和关闭每个单独项目的连接。
public void LogHttpPostStart(HttpPostRequest request)
{
try
{
//if no session is set, use the ASP.NET session
request.SessionId = GetSessionId(request.SessionId);
int eventId = (int)Model.Enums.Logging.Event.SubmittedByClient;
var current = HttpContext.Current;
if (current != null)
{
logService.AddDebug((int)request.Source, String.Format("{0} HTTP Request Details {0}", Header2Token.ToString().PadRight(HeaderTokenCount, Header2Token)),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
//Server Information
logService.AddDebug((int)request.Source, String.Format("Machine Name: {0}", current.Server.MachineName),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
//User Information
logService.AddDebug((int)request.Source, String.Format("User Host Address: {0}", current.Request.UserHostAddress),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("User Host Name: {0}", current.Request.UserHostName),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
//Browser Information
if (current.Request.Browser != null)
{
logService.AddDebug((int)request.Source, String.Format("Browser: {0}", current.Request.Browser.Browser),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("Browser Version: {0}", current.Request.Browser.Version),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("User Agent: {0}", current.Request.UserAgent),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("Is Mobile Device: {0}", current.Request.Browser.IsMobileDevice.ToString()),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
if (current.Request.Browser.IsMobileDevice)
{
logService.AddDebug((int)request.Source, String.Format("Mobile Device Manufacturer: {0}", current.Request.Browser.MobileDeviceManufacturer),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("Mobile Device Model: {0}", current.Request.Browser.MobileDeviceModel),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
}
logService.AddDebug((int)request.Source, String.Format("Platform: {0}", current.Request.Browser.Platform),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("Cookies Enabled: {0}", current.Request.Browser.Cookies.ToString()),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
logService.AddDebug((int)request.Source, String.Format("Frames Enabled: {0}", current.Request.Browser.Frames.ToString()),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
if (current.Request.Browser.JScriptVersion != null)
{
logService.AddDebug((int)request.Source, String.Format("Javascript Version: {0}", current.Request.Browser.JScriptVersion.ToString()),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
}
}
logService.AddDebug((int)request.Source, String.Format("{0} End HTTP Request Details {0}", Header2Token.ToString().PadRight(HeaderTokenCount, Header2Token)),
siteId: request.SiteId, epayCustomerId: request.EPayCustomerId, sessionId: request.SessionId,
eventId: eventId);
}
}
catch (Exception ex)
{
handler.HandleError(true, ex);
}
try
{
logService.SaveChanges();
}
catch (Exception ex)
{
handler.HandleError(true, ex);
}
}
答案 0 :(得分:1)
第一个问题是您在应用程序期间保持打开DbContext。最佳实践是仅在需要时对其进行实例化,然后进行处理。但更大的问题是你在多线程环境中使用你的LoggingService
(如果我理解正确的话),但DbContext不是线程安全的。请参阅此SO question以及ScottGu's post上的评论(搜索单词thread)。因此,您应该以线程安全的方式保存日志条目,而不是在DbContext中,只在您想要访问数据库时打开DbContext。
+1而不是InitializeLog()
方法,请查看System.Lazy<T>
答案 1 :(得分:1)
可能是EF中的错误,可能是代码中的错误,很难说。如果您发布实体类的定义,我们可以重现问题,否则很难看到它。您也可以通过隔离代码并使用伪随机数据在无限循环中运行日志记录来尝试它,直到它再次发生。
但是,如果可以的话,很少有。您对日志服务中初始化的上下文有点偏执。如果在构造函数中初始化它,则无法在以后初始化它。由于您已经在使用容器,为什么不将上下文作为构造函数的参数并让容器为您注入它。你的班级基本上是一个控制狂(反模式)。
public class LoggingService : ILoggingService
{
Logging.Model.MyLogging logging;
public LoggingService(MyLogging logging)
{
// check for null here
this.logging = logging;
//no further null checks
}
....
}
此外,当您使用容器注册组件时,将其生命周期设置为http请求范围。
For<ILoggingService>().HttpContextScoped().Use<LoggingService>();
如果您这样做,请不要忘记在请求结束时销毁对象:
protected void Application_EndRequest()
{
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}
通过这种方式,您可以为每个请求获取新的对象集,这些请求也会在最后得到妥善处理。