Using WebMatrix, WCF and “You must call the WebSecurity.InitializeDatabaseConnection method before you call any other method of the WebSecurity class.” error

As an addendum to my previous post regarding using WebMatrix in WCF you may run into a situation where you receive the error “You must call the WebSecurity.InitializeDatabaseConnection method before you call any other method of the WebSecurity class.” 

Should such a situation arise you might quickly discover that simply placing the initialization code into the Application_Start event handler as you normally would does not work. This is because Application_Start is part of the http pipeline and will only get invoked if a http request is made.

So whats the solution? A little known feature of the App_Code folder which basically allows you to create a global Application Start hook regardless of protocol exactly like you assume the Application_Start handler is doing. This is done by implementing any class that contains a static void AppInitialize().

In other words you can then do this.

public class App
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    //This is the key, any class that implements this method that lives in the App_Code folder will work
    public static void AppInitialize()
    {
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

    public class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
        }
    }

}

And that’s it, you should be all good…