I have a repository that needs to be created per request. Now there is a singleton caching object that needs to use that repository to fill itself with data, but this object is initialized in the Application_Start event, therefore there is not request context.
Which would be the best way of accomplish this with Ninject?
Thanks.
As current
HttpContextis missing on app startup (in IIS7 integration mode) Ninject will definitely treat object bindedInRequestScopeas it would be inInTransientScopewhen you try to inject dependency on app startup. As we can see in Ninject's (2.2) source code:HttpContext.Currentwill benullat app startup, so theInRequestScopebinded object will be treated on app startup the same way as it would be bindedInTransientScope.So you can have in your
global.asax:But you will have to do cleanup after use of
RequestScopeObject(e.g.Dispose()it, if it implementsIDisposable).Another approach
Bind your
RequestScopeObjectbothInRequestScopeandInSingletonScopeutilizing the conditional binding like this:The cleanup after initialization remains the same.