24

I want when my application starts, to execute some code

   if (!WebMatrix.WebData.WebSecurity.Initialized){
           WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

There is a folder App_start at the project, but I didn't find any file that I can add this code. Do you know if there is a specific file that has this purpose?

2

3 Answers 3

41

Put your code in static method inside a class.

public static class SomeStartupClass
{
    public static void Init()
    {
        // whatever code you need
    }
}

Save that in App_Start. Now add it to Global.asax, along with the other code MVC initialises here:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();

    SomeStartupClass.Init();
}

Now your startup code is separated nicely.

Sign up to request clarification or add additional context in comments.

1 Comment

I've faced with the next problem: Startup's Configuration method executes every time, when user sends request to Web application (call controller's method). But I need to execute my method just only once, when I start application
31

This kind of startup code typically goes in the Application_Start() method, Global.asax.cs file

Comments

4

Use the following in the Global.asax:

protected void Application_Start(object sender, EventArgs e)
{

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.