0

Currently, my MVC 3 app has a dependency on a static class that is initialized in the Application_Start() like this:

protected void Application_Start()
{
    MyDependency.Initialize();
}

With the static class looking more or less like the following:

public static class MyDependency
{
    public static void Initialize()
    {
        // Perform some I/O...
    }
}

This dependency is used in an attribute class, which comes with the caveat of having no run-time dependencies (hence the call to initialize in the Application_Start())

public class MyAttributeClass : ...
{
    public MyAttributeClass()
    {
        MyDependency.DoSomething(); //...
    }
}

Ultimately, other developers in our shop will have to use this API, and I'd like to see if there's a way to get rid of the line in the Application_Start() (an extra line of code in the Global.asax is likely to be a forgotten step)

For instance, is there a way the MyDependency class can "hook" into the pipeline without the needing to edit the Global.asax?

Didaxis
  • 8,486
  • 7
  • 52
  • 89

2 Answers2

3

Use a static constructor in MyDependency. Here's the MSDN explaining the functionality static constructors provide.

By using a static constructor you should then be able to perform all the IO you need, as the constructor will be run before any static members are accessed.

Lukazoid
  • 19,016
  • 3
  • 62
  • 85
  • Yup this did it. I was under the (wrong) impression that the static constructor was called when the static class is first used. The MSDN article clarified things. Thank you – Didaxis Jan 31 '12 at 18:09
  • This certainly works. However, be very cautious that your static constructor does not throw any exception as has nasty consequences. See http://stackoverflow.com/a/4737910/117625 and the warnings in the MSDN link from the above answer. – Ed Chapel Jan 31 '12 at 18:32
0

You should look at WebActivator. From the wiki:

WebActivator is a NuGet package that allows other packages to easily bring in Startup and Shutdown code into a web application. This gives a much cleaner solution than having to modify global.asax with the startup logic from many packages.

Essentially, you'll need something like:

using System;

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyDependency), "Initialize")]
public static class MyDependency
{
    public static void Initialize()
    {
        // Perform some I/O...
    }
}
Ed Chapel
  • 6,842
  • 3
  • 30
  • 44