In the following two cases, if Customer is disposable (implementing IDisposable), I believe it will not be disposed by ASP.NET, potentially being the cause of a memory leak:
[WebMethod]
public Customer FetchCustomer(int id)
{
return new Customer(id);
}
[WebMethod]
public void SaveCustomer(Customer value)
{
// save it
}
This (alleged) flaw applies to any IDisposable object. So returning a DataSet from a ASP.NET web service, for example, will also result in a memory leak – the DataSet will not be disposed [EDIT: This post claims that Dispose on a DataSet does nothing, so maybe this isn’t such a problem]
In my case, Customer opened a database connection which was cleaned up in Dispose – except Dispose was never called resulting in loads of unclosed database connections. I realise there a whole bunch of bad practices being followed here, but the point is that ASP.NET – the (de)serializer – is responsible for disposing these objects, so why doesn’t it?
This is an issue I was aware of for a while, but never got to the bottom of. I’m hoping somebody can confirm what I have found, and perhaps explain if there is a way of dealing with it.
This is really a problem with your design, not with ASP.NET. The
XmlSerializerit uses to serialize objects over SOAP doesn’t know anything about the objects being serialized or whether or not they implementIDisposable. Moreover, it’s not immediately apparent that they should be disposed, even if they do implementIDisposable; you might be returning a singleton instance, or an object in the cache.Web services should accept and return message classes, AKA proxy classes, aka Data Transfer Objects, which are very simple, lightweight POCO classes without any real state or intelligence and especially no ownership of unmanaged resources.
You can use a tool like AutoMapper to quickly and easily map between your domain model classes like
Customer(which apparently holds onto a database connection) and the DTOs that your web service uses.