0

I'm having troubles getting my head around a problem of mine.

My MVC application uses a number of separate databases for different clients (dont ask.). I'm using Ninject to inject a DbContext into services and controllers on a request basis like so:

var ContextFactory = new Func<MyContext>(() => { 
 var client = UserProfile.GetProfile()
 .SelectedCompany.Features.OfType<feature_Client>()
 .FirstOrDefault();
 if(client == null)
 return (DbContext)null;
 return new MyContext(client.ConnectionString);
});
Bind<MyContext>().ToMethod(x => ContextFactory ()).InRequestScope();

This works sort of well. Problem begins when i have a long running task that i run on a separate thread and return the MVC Action directly, then the context goes out of scope.

Is there any way of preventing the Context going out of scope and being dissposed?

Another problem is with filters. Im using a ActionFilter to check if a user has access to a specific function but this is some how not in the request context so i cant inject the correct dbcontext the filter looks like this:

public class AccessFilterAttribute : ActionFilterAttribute
{
 private MyContext Context;
 public RightsEnum AccessMask { get; set; }
 public AccessFilterAttribute()
 : this(DependencyResolver.Current.GetService(typeof(MyContext)) as MyContext) 
 {
 }
 public AttestAccessFilterAttribute(MyContext Context)
 {
 this.Context= Context;
 }

This work if change InRequestScope to for example ThreadScope but this makes for "bleed overs" between users. It feels like im missing something and there is some better way to do this.

Im hoping that some one has some insight on how to do this differently.

asked Oct 23, 2013 at 9:08
3
  • Custom Scope might be the way to go. Have a look here and here and here! Commented Oct 23, 2013 at 10:07
  • @MaxS-Betclic: Well that was my though. But im struggeling to come up with a good context to scope to. I tried with .InScope(s => HttpContext.Current.Session); and that seems to work. But im not quite sure what implications that might have. Commented Oct 23, 2013 at 13:06
  • Session Time might be too long for a context lifetime. The shortest it is, the better. Why won't you focus first on your long running tasks trying to reduce it, if feasible? Commented Oct 23, 2013 at 13:22

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.