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;
//container.EnablePerWebRequestScope();
//container.Register<QDHDataContext>(new PerScopeLifetime());
}
}
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;
container.EnablePerWebRequestScope();
container.Register<QDHDataContext>(new PerScopeLifetime());
but this just throws this error on startup: Container.ScopeManagerProvider is not MixedLightInjectScopeManagerProvider
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
}
Injecting dbcontext with LightInject
I'm trying to inject an EF dbcontext into a controller and have tried the following ways:
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:
but this just throws this error on startup: Container.ScopeManagerProvider is not MixedLightInjectScopeManagerProvider
How about registering the composition like this?
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:
Similarly using npoco:
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:
is working on a reply...