如何从oData V4 API操作返回IQueryable [英] How to return IQueryable from an oData V4 api action

查看:51
本文介绍了如何从oData V4 API操作返回IQueryable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照教程

Following the tutorial here I'm trying to return IQueryable but I get error The operation cannot be completed because the DbContext has been disposed

public class ProductsController : ODataController
{
    [EnableQuery]
    public IQueryable<Product> Get()
    {
        return GetRepository<Product>().GetQueryable();
    }
}

GetRepository()本质上是较大的通用DI和工作单元模式类的一部分

GetRepository() is part of a larger generic DI and Unit of work pattern class that basically

public Repository(DbContext context)
{
    Context = context;
    DbSet = Context.Set<T>();
}

public virtual IQueryable<T> GetQueryable()
{
    IQueryable<T> query = DbSet;

    return query;
}

推荐答案

从控制器返回IQueryable时,您无法控制该IQueryable的运行时间.发生的情况是,在Web API管道开始运行IQueryable并返回结果之前,就已经处置了DbContext.

When you return an IQueryable from a controller, you don't have control over when that IQueryable is run. What is happening is that your DbContext is being disposed before the Web API plumbing is getting around to running the IQueryable and returning the results.

您对GetRepository所做的事情称为服务定位器模式.但是,Web API具有进行依赖注入的机制,这将使您对资源的生存期有更多的确定性控制.

What you are doing with GetRepository is referred to as the Service Locator Pattern. However Web API has a mechanism for doing Dependency Injection, which will give you more deterministic control of the lifetime of your resources.

https://www.asp.net/web-api/overview/advanced/dependency-injection

使用这种方法,构造函数将注入服务(GetRepository的返回类型),然后在控制器上覆盖Dispose,以便清理构造函数注入的服务.一旦完成运行并从IQueryable返回结果,Web API就会在您的控制器上调用Dispose,因此您的生命周期问题将得到解决.

Using this approach, you constructor inject your services (the return type of GetRepository), and then override Dispose on your controller so you can clean up your constructor injected services. Web API will call Dispose on your controller once it has finished running and returning the results from your IQueryable, and thus your lifetime issues will be fixed.

NuGet上有许多常见的IOC容器的包装程序,以使它们可以自动与Web API一起使用.

There are wrappers on NuGet for many of the common IOC containers to allow them to work automatically with Web API.

这篇关于如何从oData V4 API操作返回IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆