Wednesday 23 May 2012

Memory leak upgrading Enterprise Library from 3.1 to 5.0

La versión en castellano de este artículo puede encontrarse AQUÍ

I have been working recently in upgrade a project from .Net 3.5 to .Net 4 and in the way I have upgrade the Enterprise Library from version 3.1 to 5.0 and started using Unity, as it is no longer part of the entlib.

During the upgrade I did some of our tailored changes to the library, mainly the Data and Caching blocks, without much problems, as the code is still quite similar in the areas that required changes.

But once I started to test the application I noticed a big memory leak on it. Initially it wasn't obvious by I managed to work out a way to reproduce it consistently.

Using the profiler of my choice (YourKitProfiler, very nice tool indeed!) I found out that there were a nice leak of Unity objects. Monitoring were those objects were being created I ended up in the method we used to get a new database connection.

DatabaseProviderFactory factory = new DatabaseProviderFactory();  
SqlDatabase db = factory.CreateDefault() as SqlDatabase;  

Our usage of the Provider Factories wasn't the proper one as we weren't disposing them and we were creating a new instance each time we needed a database connection.

Looks like the usage of Unity as part of the enterprise library started to create a complex graph of objects each time you instantiate one of the factories, so if you don't dispose them properly the GC is not able to remove them.

I fixed the problem by using an static instance of the provider, so I use always the same object each time I need a database connection. Another option would have been wrapping that piece of code inside an using block, but it is up to you.

I assume a similar problem is present if you use of any of the Provider Factories in the Enteprise Library, not only on the Database one, so if you find that you have a memory leak in your application after upgrading from version 3.1, have a look at the way you use them.

Update: looks like disposing your providers doesn't work. Each time you create an instance of one of them the configuration file is parsed and an object graph representing it  is created by Unity, which seems its not disposed even if you dispose the provider. So try to reduce the number of providers you create to a minimun, using a singleton for example could be a good idea.

No comments:

Post a Comment