Search code examples
c#asp.netasp.net-mvcdependency-injectionsimple-injector

Web app instancing performance hit with dependency injection


I have a asp.net mvc app where a lot of things are dependent on knowing the url of the web request (it's multi-tenant). Currently the HttpContext is being injected in a lot of constructors (through a wrapper that sets up some variables based on the context) using Simple Injector. This means that most things have to be instanced "per web request" vs per application.

Now what I could do here is just pass the HttpContext wrapper, or only the required data, in methods rather that constructor injection.

What I would like some clue on is the actual performance difference. Because it does make it a lot less elegant having to always pass the wrapper/data. This is however a quite high-traffic site so I will definitely consider changing it up.

I do realize this depends a bit on what's going on in the constructor, but assume that all it does is assign dependencies.

To clarify I do not have a specific performance problem. This is only optimization and I'm wondering if it's worth going through the work of refactoring to achieve this.


Solution

  • Instead of just a wrapper you can place a provider in between, which you could be singleton, which makes it possible for all consumers to be singleton as well.

    Like this:

    public interface IHttpContextProvider
    {
        HttpContext CurrentContext { get; }
    }
    
    public class HttpContextProvider : IHttpContextProvider
    {
        public HttpContext CurrentContext => HttpContext.Current;
    }
    
    public interface IMyContextWrapper
    {
        string CurrentRoute { get; }
    }
    
    public class MyContextWrapper : IMyContextWrapper
    {
        private readonly IHttpContextProvider httpContextProvider;
    
        public MyContextWrapper(IHttpContextProvider httpContextProvider)
        {
            this.httpContextProvider = httpContextProvider;
        }
    
        public string CurrentRoute 
        {
            get
            {
                var context = this.httpContextProvider.CurrentContext;
                return informationFromContext;
            } 
        }
    }