c# - ObjectContext disposal in EF + Repository ASP.NET MVC 3 application -


so, i'm getting the objectcontext instance has been disposed , can no longer used operations require connection. error when try access objectcontext through repository in onactionexecuting actionfilterattribute.

my actionfilterattribute checks existence of http cookie. if exists verifies database, refreshes it's expiration, , adds controller viewdata collection can accessed actionresult's. if doesn't exist, redirects user login page.

the filter half works because when http cookie does exist , attempts grab concrete object out of database, crashes above error message.

because of number of layers in place, i'm gonna go ahead , post code of them, verifycookieattribute.cs, cookierepository.cs , repository_1.cs. lastly, although not make difference, error occurs in selectsingle method of repository_1.cs.

dependency injection ninject 2.2.1.0. lazy loading enabled, either setting produces same error.

anyway, i'd appreciate guidance in i'm going wrong of this. in advance help!

//  verifycookieattribute.cs [attributeusage(attributetargets.class, allowmultiple = false, inherited = true)] internal class verifycookieattribute : actionfilterattribute {     [inject]     public cookierepository repository { private get; set; }      private httprequestbase request = null;     private httpresponsebase response = null;      private readonly bool administration = false;     private readonly bool customers = false;      private readonly string[] excludedpaths = new string[2] {         "/administration",         "/customers"     };      public verifycookieattribute(         bool administration,                     bool customers) {     this.administration = administration;     this.customers = customers; }      public override void onactionexecuting(         actionexecutingcontext actionexecutingcontext) {         this.request = actionexecutingcontext.httpcontext.request;          if (!this.excludedpaths.contains(this.request.url.absolutepath)) {             this.response = actionexecutingcontext.httpcontext.response;              if (this.exists()) {                 cookie cookie = this.get();                  this.refresh(cookie);                  actionexecutingcontext.controller.viewdata.add("cookie", cookie);                  if (this.administration) {                     actionexecutingcontext.result = new redirecttorouteresult(new routevaluedictionary(new {                         area = "administration",                         controller = "administration",                         action = "dashboard"                     }));                 } else if (this.customers) {                     //  nothing                 };             } else if (!this.exists() && !this.response.isrequestbeingredirected) {                 if (this.administration) {                     actionexecutingcontext.result = new redirecttorouteresult(new routevaluedictionary(new {                         area = "administration",                         controller = "administration",                         action = "default"                     }));                 } else if (this.customers) {                     actionexecutingcontext.result = new redirecttorouteresult(new routevaluedictionary(new {                         area = "customers",                         controller = "customers",                         action = "default"                     }));                 };             };         };     }      private bool exists() {         string token = this.gethttpcookietoken();          return (!string.isnullorempty(token) && (token.length == 256));     }      private cookie get() {         string token = this.gethttpcookietoken();          cookie cookie = this.repository.selectsingle(             c =>                 (c.token == token));          return (cookie);     }      private string gethttpcookietoken() {         if (this.request.cookies["nwp"] != null) {             return this.request.cookies["nwp"]["token"];         };          return (string.empty);     }      private void refresh(         cookie cookie) {         if (cookie.refreshstamp <= datetime.now.addhours(1)) {             this.repository.refreshcookie(cookie.cookieid);              this.sethttpcookie(cookie);         };     }      private void sethttpcookie(         cookie cookie) {         this.response.cookies["nwp"]["token"] = cookie.token;         this.response.cookies["nwp"].expires = cookie.refreshstamp.addhours(1);     } }  //   cookierepository.cs public sealed class cookierepository : repository<cookie> {     [inject]     public cookierepository(         entities entities)         : base(entities, true) {     }      public void refreshcookie(         int cookieid) {         this.entities.executefunction("refreshcookie", new objectparameter("cookieid", cookieid));     } }  //  repository`1.cs public class repository<tentity> : irepository<tentity> tentity : class {     protected readonly entities entities = null;      private readonly iobjectset<tentity> entityset = null;      [inject]     public repository(         entities entities)         : this(entities, true) {     }      [inject]     public repository(         entities entities,         bool createentityset) {         this.entities = entities;          if (createentityset) {             this.entityset = this.entities.createobjectset<tentity>();         };     }      public virtual void delete(         tentity tentity) {         this.entityset.deleteobject(tentity);     }      public virtual void insert(         tentity tentity) {         this.entityset.addobject(tentity);     }      public virtual iqueryable<tentity> select() {         return this.entityset;     }      public virtual iqueryable<tentity> select(         expression<func<tentity, bool>> selector) {         return this.entityset.where(selector);     }      public virtual bool selectany(         expression<func<tentity, bool>> selector) {         return this.entityset.any(selector);     }      public virtual ilist<tentity> selectlist() {         return this.entityset.tolist();     }      public virtual ilist<tentity> selectlist(         expression<func<tentity, bool>> selector) {         return this.entityset.where(selector).tolist();     }      private ilist<tentity> selectorderedlist(         bool ascending,         params expression<func<tentity, icomparable>>[] orderers) {         iorderedqueryable<tentity> queryable = null;          foreach (expression<func<tentity, icomparable>> orderer in orderers) {             if (queryable == null) {                 queryable = (ascending ? this.entityset.orderby(orderer) : this.entityset.orderbydescending(orderer));             } else {                 queryable = (ascending ? queryable.thenby(orderer) : queryable.thenbydescending(orderer));             };         };          return (queryable.tolist());     }      public virtual ilist<tentity> selectorderedlist(         params expression<func<tentity, icomparable>>[] orderers) {         return this.selectorderedlist(true, orderers);     }      public virtual ilist<tentity> selectordereddescendinglist(         params expression<func<tentity, icomparable>>[] orderers) {         return this.selectorderedlist(false, orderers);     }      public virtual tentity selectsingle(         expression<func<tentity, bool>> selector) {         return this.entityset.single(selector);     }      public virtual void update() {         this.entities.savechanges();     }      public virtual ienumerable<tentity> where(         expression<func<tentity, bool>> selector) {         return this.entityset.where(selector);     } } 

update

here's stack trace per @jfar's request:

system.data.objects.objectcontext.ensureconnection() +8550458 system.data.objects.objectquery1.getresults(nullable1 formergeoption) +46 system.data.objects.objectquery1.system.collections.generic.ienumerable<t>.getenumerator() +44 system.linq.enumerable.single(ienumerable1 source) +184 system.data.objects.elinq.objectqueryprovider.b_3(ienumerable1 sequence) +41 system.data.objects.elinq.objectqueryprovider.executesingle(ienumerable1 query, expression queryroot) +59 system.data.objects.elinq.objectqueryprovider.system.linq.iqueryprovider.execute(expression expression) +150 system.linq.queryable.single(iqueryable1 source, expression1 predicate) +300 {withheld}.repositories.repository1.selectsingle(expression1 selector) in c:\projects{withheld}{withheld}\repositories\repository1.cs:98 verifycookieattribute.get() in c:\projects\{withheld}\{withheld}\attributes\verifycookieattribute.cs:100 verifycookieattribute.onactionexecuting(actionexecutingcontext actionexecutingcontext) in c:\projects\{withheld}\{withheld}\attributes\verifycookieattribute.cs:55 system.web.mvc.controlleractioninvoker.invokeactionmethodfilter(iactionfilter filter, actionexecutingcontext precontext, func1 continuation) +47 system.web.mvc.<>c_displayclass17.b_14() +19 system.web.mvc.controlleractioninvoker.invokeactionmethodfilter(iactionfilter filter, actionexecutingcontext precontext, func1 continuation) +263 system.web.mvc.<>c__displayclass17.<invokeactionmethodwithfilters>b__14() +19 system.web.mvc.controlleractioninvoker.invokeactionmethodfilter(iactionfilter filter, actionexecutingcontext precontext, func1 continuation) +263 system.web.mvc.<>c_displayclass17.b_14() +19 system.web.mvc.controlleractioninvoker.invokeactionmethodfilter(iactionfilter filter, actionexecutingcontext precontext, func1 continuation) +263 system.web.mvc.<>c__displayclass17.<invokeactionmethodwithfilters>b__14() +19 system.web.mvc.controlleractioninvoker.invokeactionmethodwithfilters(controllercontext controllercontext, ilist1 filters, actiondescriptor actiondescriptor, idictionary2 parameters) +191 system.web.mvc.controlleractioninvoker.invokeaction(controllercontext controllercontext, string actionname) +343 system.web.mvc.controller.executecore() +116 system.web.mvc.controllerbase.execute(requestcontext requestcontext) +97 system.web.mvc.controllerbase.system.web.mvc.icontroller.execute(requestcontext requestcontext) +10 system.web.mvc.<>c__displayclassb.<beginprocessrequest>b__5() +37 system.web.mvc.async.<>c__displayclass1.<makevoiddelegate>b__0() +21 system.web.mvc.async.<>c__displayclass81.b_7(iasyncresult ) +12 system.web.mvc.async.wrappedasyncresult`1.end() +62 system.web.mvc.<>c_displayclasse.b_d() +50 system.web.mvc.securityutil.b_0(action f) +7 system.web.mvc.securityutil.processinapplicationtrust(action action) +22 system.web.mvc.mvchandler.endprocessrequest(iasyncresult asyncresult) +60 system.web.mvc.mvchandler.system.web.ihttpasynchandler.endprocessrequest(iasyncresult result) +9 system.web.callhandlerexecutionstep.system.web.httpapplication.iexecutionstep.execute() +8862381 system.web.httpapplication.executestep(iexecutionstep step, boolean& completedsynchronously) +184

i assume using mvc 3.

in previous versions of asp.net mvc, action filters create per request except in few cases. behavior never guaranteed behavior merely implementation detail , contract filters consider them stateless. in asp.net mvc 3, filters cached more aggressively. therefore, custom action filters improperly store instance state might broken.

this means attributes not created every request, therefor inrequestscope injection won't work. need either inject iserviceprovider , repository on each request or create new context manually.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -