简体   繁体   中英

ASP.NET WebApi action dispose after serialization?

I have a WebApi controller action that returns an enumerable. I have a MediaTypeFormatter hooked up that understands how to serialize this enumerable. 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. 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:

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

  • ApiControllers are disposable, so you can dispose your enumerable there too. This works as webapi always makes sure to dispose it once response is written out. In fact a controller instance is registered just like the above mentioned point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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