【问题标题】:When using Unity DI how to add Non DI Service with Entity Framework使用 Unity DI 时如何使用实体框架添加非 DI 服务
【发布时间】: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));
        }
    }
}

}

【问题讨论】:

标签: entity-framework asp.net-web-api unity-container


【解决方案1】:

由于我使用实体的 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
    }
}

过滤器或全局过滤器是可能需要此功能的一个示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多