Friday, 15 August 2014

asp.net mvc - How to pass a unit of work / entity context across Action filters and Controllers -



asp.net mvc - How to pass a unit of work / entity context across Action filters and Controllers -

i trying create sure mvc application uses 1 dbcontext per request in order cut down number of times db connection open , there no concurrency issues.

this means need utilize same context in global action filters controllers.

i have tried

public class layoutfilter : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext filtercontext) { membershipuser loggedinuser = membership.getuser(); myunitofwork uow = new myunitofwork(); viewbag.fullname = uow.userservice.getuser().fullname filtercontext.actionparameters["unitofwork"] = uow; } }

however context disposed when seek read controller shown below

public actionresult logout(myunitofwork uow) { viewbag.something = uow.exampleservice.getmyobject(); homecoming redirecttoaction("login"); }

i same issue context beingness disposed when seek share same unitofwork object casting property of base of operations controller class

public class basecontroller : controller { public requestboxunitofwork unitofwork; } public class layoutfilter : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext filtercontext) { membershipuser loggedinuser = membership.getuser(); basecontroller basecontroller = (basecontroller)filtercontext.controller; viewbag.fullname = basecontroller.unitofwork.userservice.getuser().fullname filtercontext.actionparameters["unitofwork"] = uow; } }

the context disposed when seek access in controller , have read in few places should not utilize base of operations controller class unsure of can do.

what recommended ways share entity context between actionfilters , controllers

create dbcontext part of controller setup, , have available via internal property on controller.

public class mycontroller : controller { private myunitofwork unitofwork; internal myunitofwork unitofwork { { homecoming unitofwork; } } }

you able access context in filter attribute this:

mycontroller controller = (mycontroller)filtercontext.controller myunitofwork uow = controller.unitofwork;

there's no need pass unit of work action method in controller, because controller has object, , can accessed via same internal property.

asp.net-mvc entity-framework controller action-filter

No comments:

Post a Comment