Entity Framework and the PreApplicationStartMethod attribute

Recently, while implementing an EntityFramework data model into a new application, I thought I’d add some caching functionality early, to establish a framework going forward. I added the DBML (generated from a database), and added in my funky caching layer (which will be distributed as a Nuget package soon) that allows caching to be configurable switching between in memory, ASP.NET cache and AppFabric caching.

Anyway, I added some repository methods to grab data from the database. All good. I added my caching layer to that so that a bunch of reference data was cached, again all good.

Now this application is a .NET 4/ASP.NET MVC 3 application and I was using the PreApplicationStartMethod attribute to specify a class method that is executed before anything else in the application. Something like this:-

In the AssemblyInfo.cs file I had this attribute declaration:

[assembly: PreApplicationStartMethod(typeof(WebAppStart), "PreStartInitialise")]

And in the WebAppStart.cs file I had this:

public static class WebAppStart
{
    public static void PreStartInitialise()
    {
        RegisterWebDependencies();
    }
}

This all worked well. Then I thought, well rather than let the first user of the application cause the cache to get primed/filled, I would simply make a call to a method I had already to prefill the cache:

public static void PreStartInitialise()
{
    RegisterWebDependencies();
    PrimeCache();
}

Seems ok so far, but alas no. Apparently, you cannot use the EntityFramework from within a method invoked by the PreApplicationStartMethod attribute. What you will get is an exception message like this:

RealExceptionMsg

The solution was easy enough for me, I just moved the PrimeCache method to the Application_Start event within the Global.asax.cs file. However, what made this error, let’s say “interesting” is that I was developing an azure application. What then happens is you get an error that seemingly has nothing to do with the root cause. So when developing running in debug mode for an azure application you get the following exception:

 

ExceptionOnRunningApp

It seems to point to some issue with the connection string which is absolute rubbish and leads you to nowhere. If you happen to try and run this without attaching a debugger, then you simply get an exception dialog stating that the windows azure web role has stopped working.

ExceptionMsg 

Nice.

So, the moral to this story. Don’t use EntityFramework within a method defined using the PreApplicationStartMethod attribute. If developing an azure app and you get this error, do not believe what you are told. Move the EntityFramework code to somewhere later in the lifecycle and you will be good.

1 Comment

Comments have been disabled for this content.