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.

Patrik
  • 255
  • 3
  • 11
  • Custom Scope might be the way to go. Have a look [here](http://stackoverflow.com/questions/5784917/how-to-create-a-ninject-custom-scope-that-returns-the-same-object-until-that-obj) and [here](https://github.com/ninject/ninject/wiki/Object-Scopes) and [here](http://books.google.com/books?id=YY39AAAAQBAJ&pg=PT67&lpg=PT67&dq=custom+scope+ninject&source=bl&ots=WUEI1r1Fwo&sig=OXtQYaXl11BeHqwZzyDoxZaxVkY&hl=en&sa=X&ei=S59nUp6XIqmX0AXpyYDYBg&redir_esc=y#v=onepage&q=custom%20scope%20ninject&f=false)! – MaxSC Oct 23 '13 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. – Patrik Oct 23 '13 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? – MaxSC Oct 23 '13 at 13:22

0 Answers0