使用 Unity DI 时如何使用 Entity Framework 添加非 DI 服务

When using Unity DI how to add Non DI Service with Entity Framework

这显然是一个不同于 Multithreading issue 的问题。

将 Unity 与依赖注入 (DI) 用于我的所有服务,并使用 entity framework 似乎已初始化且工作正常的上下文。

目前正在使用 .net 4.5 和 mvc,Unity.WebApi 和 entity framework 6.0.0.0.

我想知道是否可以在此模型中持久化服务或在 DI 外部使用,并能够关闭并重新初始化持久化服务中的 entity framework 如果可能的话。

当我尝试通过堆栈持久化服务时出现此错误 class 因此它的性能会非常快 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 table 用于记录目的。

这是我为什么要尝试持久服务的代码片段:

    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));
        }
    }
}

}

由于我已将我的服务副本与实体的 DBContext 一起存储,因此它失败了,因为它正被多个线程使用。修复是每次都更新它,因为它最初来自 Unity DI 解析器方法,并且每次调用存储的服务及其方法时实体都不会更新。

未知是否可以通过不同或更好的方式清除当前上下文,以使其在特定 Web api 线程或端点中完成特定用例场景时执行得更快,而不是更新它在保存的服务的每个方法调用中。

每次将其存储在静态变量中并在每个方法上重复使用时的解决方案:

// some service
public class SomeSerivce : ISomeService
{
...
   // when the service is stored must use new context liberally
   public void SomeStaticMethod() {
        _DavinciEntities = new DavinciEntities();
    ... // work
    }
}

过滤器或全局过滤器可能需要的示例。