How to inject application_start(MVC)

Nov 19, 2013 at 8:59 AM
hallo ,
I am a beginner in dependency Injection and unity ,and I was trying to find a way to inject application_start.
In apploication_start i have a static class that i am trying to call with the injected objects ,but how can i do that ?

for me it sounds so stupid to do something like this(cuz the unity Container is definded there) ,but still I am finding no way to call a method just once except in application_start .
any tipps please ?
Thanks for ur help :)
Nov 20, 2013 at 2:09 AM
If you use the Unity bootstrapper for ASP.NET MVC it will add code to the App_Start folder (marked with the WebActivatorEx.PreApplicationStartMethod attribute) that gets executed at application startup.

The package will also install UnityDependencyResolver used to resolve your objects. This article looks pretty good at presenting a walkthrough: Microsoft Unity in ASP.NET MVC.

Randy Levy
Enterprise Library support engineer
Support How-to
Nov 20, 2013 at 8:31 AM
I am not talking about resolving an object in the Project ,but in application_start(just at the beginning of the hall of the mvc project)
i can not inject this method because ,before calling this method still no injected objects has been resolved .

thx for the link but it did not help me
Nov 20, 2013 at 7:57 PM
There's no way to automatically inject those dependencies into the Application_Start class, but it as simple as calling container.Resolve<T>:
public class MvcApplication
    private static ISomeService service;

    protected void Application_Start(object sender, EventArgs e)
        var container = CreateInitializedContainer();

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        service = container.Resolve<ISomeService>();
One warning though: storing dependencies into static fields will effectively make those services (and their dependencies, and the dependency's dependencies) singleton. Those services will probably be called from multiple threads/requests simultaneously so you must ensure that the complete object graph is thread-safe.