asp.net-mvc-5structuremap3

Current URL from PreApplicationStart


I am using StructureMap.MVC5 which relies on the PreApplicationStart method to register an HttpModule and initialize the IoC container. Is it possible to get the server name the page is executing on at this point so that I can set an environment specific property in the IoC initialization?


Solution

  • I was able to resolve this issue by moving the IoC initialization to the Application_BeginRequest method, where the HttpContext has already been set. In order to ensure that the IoC container was not reinitialized on each call to Application_BeginRequest, I was able to use a mutex block, thus negating the need to move this code to somewhere earlier in the page lifecycle.

    public class FirstInitialization
    {
        private static Object s_lock = new Object();
    
        public static string URL { get; protected set; }
    
        // Initialise only on the first request
        public static string Initialize(HttpContext context)
        {
            if (string.IsNullOrEmpty(URL))
            {
                lock (s_lock)
                {
                    if (string.IsNullOrEmpty(URL))
                    {
                        URL = HttpContext.Current.Request.Url.AbsoluteUri;
                    }
    
                    DependencyResolver.SetResolver(IoC.GetDependencyResolver(URL));
    
                }
            }
    
            return URL;
        }
    }