c# - Ninject: Is it possible to have parent object in SingletonScope and child in TransientScope? -
i have been racking brain on , off few weeks now... currenlty have this:
- a bunch of
*service
classes - all of these depend on different
*repository
classes access database via ef - to allow unit testing derivate of
dbcontext
injected repositories. (so can not useusing
dispose of contexts)
to correctly dispose of ef contexts injected run dependency tree in inrequestscope()
or in simple custom scope - inscope(c => new object())
on top level , in inparentscope()
on other levels.
both of these approaches create , dispose lot of objects during each request. in addition talking single page application 95% of queries (50 or so) executed during 2 requests inrequestscope()
seems not idea. *service
classes hold no state , insingletonscope()
, minimize amount of object creation.
the question
is possible have parent *service
, *repository
classes in insingletonscope()
, somehow inject ef dbcontext
in scope return new instance each time accessed , honor idisposable
using ninject?
i know dependencies injected while objects created still somehow managed?
no, it's not possible. if think it, should understand why.
a singleton object exist lifetime of application. inrequestscope object lives lifetime of request. since singleton repository live forever, , hold reference dbcontext (because it's dependency), means dbcontext cannot garbage collected without repository having mechanism release it.
even if did supply such mechanism, you'd have have mechanism re-acquire new instance on next request, because new singleton repository not created (and it's constructor not called, , it's dependencies not resolved, , not able know new dbcontext).
so, in effect, making inrequestscope object dependency of singleton object make inrequestscope object singleton, or else object disposed out under singleton , bad..
also, beg differ on fact repositories do have state. state dbcontext itself. since singleton application wide static instance, give same instance users using app, mean give same dbcontext, huge no-no, since users stomp on each others dbcontext state.
your services also, likewise, stateful because have repositories, i've pointed out have dbcontexts, stateful.
what want make services, repositories, , dbcontexts inrequestscope.
i fail understand why approach "create lots of objects during each request". whole point creates 1 instance of each object type per request.
Comments
Post a Comment