How to inject dependencies into the global.asax.cs

前端 未结 1 978
南旧
南旧 2020-12-23 20:26

How do I inject dependencies into the global.asax.cs, i.e. the MvcApplication class?

Having previously used the Service Locator (anti-)pattern for dependency injecti

1条回答
  •  猫巷女王i
    2020-12-23 20:44

    The class in your global.asax.cs is your Composition Root, so you can't (and shouldn't) inject anything into it from the outside.

    However, there's only one instance of the MvcApplication class, so if you need a service in one of its methods, you can just declare it as a member field - e.g:

    public class MvcApplication : System.Web.HttpApplication
    {
        private readonly ILogService log;
    
        public MvcApplication()
        {
            this.log = new MyLogService();
        }
    
        protected void Application_Start()
        {
            // ...
    
            this.log.Log("Application started");
        }
    }
    

    0 讨论(0)
提交回复
热议问题