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
HttpContext
is missing on app startup (in IIS7 integration mode) Ninject will definitely treat object bindedInRequestScope
as it would be inInTransientScope
when you try to inject dependency on app startup. As we can see in Ninject's (2.2) source code:HttpContext.Current
will benull
at app startup, so theInRequestScope
binded 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
RequestScopeObject
bothInRequestScope
andInSingletonScope
utilizing the conditional binding like this:The cleanup after initialization remains the same.