Press Ctrl / CMD + C to copy this to your clipboard.
This post will be reported to the moderators as potential spam to be looked at
I'm trying to inject an EF dbcontext into a controller and have tried the following ways:
public class ServiceComposer : IUserComposer
public void Compose(Composition composition)
composition.Register<QDHDataContext>(factory => new QDHDataContext(), Lifetime.Scope);
//var container = composition.Concrete as ServiceContainer;
This works the first time the controller is hit, but on subsequent attempts it throws this error: The operation cannot be completed because the DbContext has been disposed
So i tried this way:
var container = composition.Concrete as ServiceContainer;
but this just throws this error on startup: Container.ScopeManagerProvider is not MixedLightInjectScopeManagerProvider
How about registering the composition like this?
composition.Register<QDHDataContext>(factory => new QDHDataContext(), Lifetime.Request);
No, I get the same error: The operation cannot be completed because the DbContext has been disposed
Does this work?
if you need to inject parameters you can do:
composition.Register<QDHDataContext>(x=> new DbContext(para1, para2)), Lifetime.Request);
Similarly using npoco:
return new NPoco.Database(
Thanks Gareth, none of those work either :(
I'm thinking it must be the way the dbcontext is setup, or being injected into the service. (I've inherited that part of the code, and am trying to incorporate it without any changes)
If I remove the need to inject into the service, and just new up a dbcontext when needed, then I don't have a problem i.e:
public ServiceRecordService(QDHDataContext mainRepo)
_dbContext = mainRepo;
using (var db = _dbContext)
// this does NOT work
//public ServiceRecordService(QDHDataContext mainRepo)
//_dbContext = mainRepo;
using (var db = new QDHDataContext())
// this works ok
is working on a reply...
Write your reply to:
Image will be uploaded when post is submitted