【发布时间】:2017-09-13 00:17:40
【问题描述】:
这绝对是与Multithreading issue 不同的问题。
对我的所有服务使用具有依赖注入 (DI) 的 Unity,并使用似乎已初始化且工作正常的实体框架上下文。
目前使用带有 mvc 和 Unity.WebApi 以及实体框架 6.0.0.0 的 .net 4.5。
我想知道是否可以在此模型中持久化服务或在 DI 之外使用,如果可能的话,是否能够关闭并重新初始化持久化服务中的实体框架。
当我尝试通过堆栈类持久化服务时出现此错误,因此它的性能会非常快 b/c 我使用得更频繁。
The Error message I am getting is: Error Message: The underlying provider failed on Open. - The connection was not closed. The connection's current state is connecting.( at System.Data.Entity.Core.EntityClient.EntityConnection.Open()
目的是仅检索单个实体并使其加载速度比依赖注入版本更快,并通过服务公开结果。实体绑定到一个 sql 表以进行日志记录。
这是我为什么要坚持服务的代码 sn-p:
using System;
using System.Linq;
using Davinci.Models;
namespace Services.Services
{
public interface ILogService
{
void SaveLog(UserLog log);
UserLog RetreiveLog(DateTime dateTime);
}
public class LogService : ILogService
{
private DavinciEntities _DavinciEntities;
public LogService(DavinciEntities context)
{
_DavinciEntities = context;
}
private void SaveLog(UserLog log)
{
_DavinciEntities.UserLogs.Add(log);
_DavinciEntities.SaveChanges();
}
public UserLog RetreiveLog(DateTime dateTime)
{
return _DavinciEntities.UserLogs.Where(m => m.LogTime.ToShortDateString() == dateTime.ToShortDateString()).FirstOrDefault();
}
}
public static class PersistService
{
public static UserLogService userLogService {get; set;}
public static void PersistUserLog(UserLogService service)
{
IUserLogService UserLogService;
if (UserAccessLog == null)
{
UserLogService = (UserLogService)context.Configuration.DependencyResolver.GetService(typeof(UserLogService));
}
}
}
}
【问题讨论】:
-
你能贴一些代码sn-ps吗?
-
显示重现问题所需的最小代码,如minimal reproducible example 中所述。此外,请按照How to Ask 中的说明分享您的研究。此错误与重用连接已关闭的旧 DbContext 实例有关,原因是未正确处置它和/或在 DI 容器中赋予它不正确的生命周期。展示您如何配置和使用这些类。
-
好的,我展示了。谢谢你的讲座。
标签: entity-framework asp.net-web-api unity-container