I have an EF 4.2 EDMX model which I use in a multi-tenant application. I connect to about 100 databases that use the same EDM model. The first time each database is accessed, my working set goes up by ~12Mb, which seems mostly to be taken by the EDM metadata cache. The memory usage never goes back down. I would think the metadata/query cache could be shared since it is the same model.
Looking for suggestions to reduce my memory footprint, though I suspect I have no control over this.
NOTE: This same scenario is NOT a problem with CodeFirst (which we are using as well) but we have a lot of code that still uses the EDMX model and cannot convert it all right now.
Thanks!
I believe you can get what you want by caching the MetadataWorkspace yourself. This is essentially what DbContext does internally when using Code First. It’s not that easy to do, but I worked out a quick prototype that I think should work.
The basic idea here is to let EF create a MetadataWorkspace once and then cache this and use it explicitly each time you need to create a context instance. This is obviously only valid if each context instance is using the same model–i.e. the same EDMX. To make this work I created a derived ObjectContext that handles the caching:
You would then use this by creating a constructor on your DbContext class like so:
This is how it works. When you create an instance of your DbContext it in turn creates an instance of SingleModelCachingObjectContext passing in the name of the EF connection string that you want to use. It also tells DbContext to dispose of this ObjectContext when the DbContext is disposed.
In SingleModelCachingObjectContext the EF connection string is used to create a MetadataWorkspace and caches it in a static field once created. This is very simple caching and simple thread safety with a lock–feel free to make it more suited to your app’s needs.
With the MetadataWorkspace obtained, the EF connection string is now parsed to obtain the store connection string and provider. This is then used to create a normal store connection.
The store connection and cached MetadataWorkspace are used to create an EntityConnection and then an ObjectContext that will use the cached MetadataWorkspace instead of using the normal caching mechanisms.
This ObjectContext is used to back the DbContext. The Dispose Method is overridden so that the store connection does not leak. When the DbContext is disposed it will dispose the ObjectContext, which will in turn call Dispose and the store connection will be disposed.
I haven’t really tested this other than to make sure it runs. It would be very interesting to know whether or not it really helps your memory usage issues.