.net - Simple Injector: how to inject HttpContext? -
i have started using simple injector di container (mostly performance reason: if has suggestions, please let me know) of classes wrote use httpcontextbase constructor parameter. have resolved removing constructor , creating property, this:
public httpcontextbase httpcontext { { if (null == _httpcontext) _httpcontext = new httpcontextwrapper(system.web.httpcontext.current); return _httpcontext; } set { _httpcontext = value; } }
but don't solution... advices?
you should favor constructor injection on else. possible. can register httpcontextbase
follows:
container.register<httpcontextbase>(() => new httpcontextwrapper(httpcontext.current), lifestyle.scoped);
this can cause problem when calling verify()
, since during application startup httpcontext.current
null
, , httpcontextwrapper
not allow passing null constructor.
it's try keep configuration verifiable, , can change registration following:
container.register<httpcontextbase>(() => { var context = httpcontext.current; if (context == null && container.isverifying) return new fakehttpcontext(); return new httpcontextwrapper(context); }, lifestyle.scoped);
fakehttpcontext
empty httpcontextbase
implementation prevent returning null
in case container verifying. fakehttpcontext
this:
public class fakehttpcontext : httpcontextbase { }
do note httpcontext runtime data , injecting runtime data components during construction anti-pattern. instead of injecting httpcontext or abstraction on components, should create application-specific abstraction provides consumer needs (for instance user identity or tenant id). implementation of abstraction can call httpcontext.current internally prevents need httpcontext injected.
Comments
Post a Comment