简体   繁体   English

ASP.NET WebApi动作在序列化后配置?

[英]ASP.NET WebApi action dispose after serialization?

I have a WebApi controller action that returns an enumerable. 我有一个WebApi控制器操作,该操作返回一个可枚举的值。 I have a MediaTypeFormatter hooked up that understands how to serialize this enumerable. 我有一个MediaTypeFormatter,它了解如何序列化此枚举。 The problem is that the enumerable is (by design) lazily evaluated. 问题是(根据设计)对可枚举进行了延迟评估。 This would be fine except that the enumerable must be disposed after it is done being used. 可以,但必须在使用完可枚举后将其丢弃。 Unfortunately, due to the lazy evaluation if I do something like this: 不幸的是,由于懒惰的评估,如果我做这样的事情:

public IEnumerable<MyClass> Get()
{
    using (var disposableEnumerable = GetData())
    {
        return disposableEnumerable;
    }
}

then disposableEnumerable is disposed before the serializer gets a hold of it. 然后在序列化器获得它之前,就将disabledEnumerable丢弃。 This results in serialization failing because the source has been disposed. 这导致序列化失败,因为已处理源。

On the other hand, if I don't wrap it in a using statement like so: 另一方面,如果我不将其包装在using语句中,例如:

public IEnumerable<MyClass> Get()
{
    return GetData();
}

Then it is never disposed and I leak the object. 然后它永远不会被丢弃,而我会泄漏物体。

What is the best way to make sure my disposable is disposed after serialization? 确保我的一次性用品序列化得到处置的最佳方法是什么?

Note: Calling ToList on the enumerable is not an option. 注意:不能在枚举上调用ToList。 The reason I return an enumerable rather than a concrete list is for memory reasons. 我返回可枚举而不是具体列表的原因是出于内存原因。 The enumerable is large and the objects created during the enumeration process are also very large. 可枚举很大,并且在枚举过程中创建的对象也很大。

Some options to achieve this: 一些实现此目的的选项:

  • Do Request.RegisterForDispose(disposableEnumerable); Request.RegisterForDispose(disposableEnumerable); in your action. 在你的行动中。 This will result in the enumerable being disposed after your response is written out. 这将导致在写出您的答复后将所有枚举丢弃。 Note that RegisterForDispose extension is part of System.Net.Http namespace. 请注意, RegisterForDispose扩展名是System.Net.Http命名空间的一部分。

  • ApiControllers are disposable, so you can dispose your enumerable there too. ApiControllers是一次性的,因此您也可以在其中处理可枚举的对象。 This works as webapi always makes sure to dispose it once response is written out. 这是因为webapi始终确保在写出响应后立即将其处置。 In fact a controller instance is registered just like the above mentioned point. 实际上,就像上述要点一样,注册了一个控制器实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM