【问题标题】:Unity with HierarchicalLifetimeManager. Do I need a 'Using' Statement with Entity Framework与 HierarchicalLifetimeManager 统一。我是否需要带有实体框架的“使用”语句
【发布时间】:2016-10-07 19:36:16
【问题描述】:

我在 Web API 2 应用程序中使用 Unity 和实体框架。我用HierarchicalLifetimeManager.注册类型

var container = new UnityContainer();
container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());

我是否需要将所有 dbContext 调用包装在这样的 using 语句中?需要这个吗?我认为 Unity 会为我处理上下文。

using (var client = new dbContext())
{
     var result = client.Customers.toList();
}

或者我可以只使用没有using 语句的dbContext 吗?

【问题讨论】:

  • 如果你这样做var client = new dbContext(),Unity与上下文的生命周期无关。

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


【解决方案1】:

我是否需要将所有 dbContext 调用包装在 using 语句中,例如 这个?

我会说这取决于你如何使用你的上下文。举个例子:

public class Service : IService, IDisposable
{
    private DbContext _context;
    public Service(DbContext context)
    {
        _context = context;
    }

    public object Get(int id)
    {
        return _context.Customers.Find(id);
    }

    public object Update(object obj)
    {
        // Code for updating
    }

    public void Dispose()
    {
        _context.Dispose();
    }
}

如果您使用HierarchicalLifetimeManager 注册Service,则context 几乎不会被释放,因为不会释放任何服务,因此永远不会释放context。但是,上面的示例应该可以与 TransientLifetimeManager 一起正常工作。

来自MSDN

分层生命周期管理器。对于这位终身经理,至于 ContainerControlledLifetimeManager,Unity返回相同的实例 每次调用 Resolve 或 ResolveAll 方法或依赖机制注入实例时 进入其他类。

如果您改为在每个方法中处理它,那么无论您使用什么生命周期管理器,它都会被正确处理。另外,IService 的消费者不需要关心如何处理IService

public class Service : IService
{

    public object Get(int id)
    {
        using (var context = new DbContext())
        {
            return context.Customers.Find(id);
        }
    }

    public object Update(object obj)
    {
        // Code for updating
    }
}

另外,考虑一下会发生什么如果你的ServiceTransient,并被注入到ContainerController 的经理中。由于经理永远不会被处置,因此服务也不会被处置。管理器将在容器的整个生命周期内保持相同的服务实例。因此,我个人建议您将上下文的处置保持在容器控制之外。 如果你确保你有一个处置链,它可以在终身经理的帮助下很好地工作herecodereview 上有几篇文章展示了 UoW 与 Unity 处理上下文的示例。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多