'Autofac - Use the same DbContext across multiple repositories
I have a desktop app using Autofac. The framework I'm using doesn't provide hooks for dependency injection and thus the view models are instantiated using the service locator pattern.
One of my view models has two repositories that it uses. The repositories both take a single object, with is the applications DbContext.
Autofac instantiates two DbContext instances - one for each repository. The two repositories should use the same DbContext instance.
The service locator is implemented as:
ServiceLocator.Current = new ServiceLocator((type) =>
{
var resolved = _container.Resolve(type);
return resolved;
});
Where _container is an IContainer instance built thusly:
var builder = new ContainerBuilder();
/* snip */
_container = builder.Build();
How can I have Autofac use the same DbContext for all dependencies when creating the instance of the view model?
I definitely don't want a singleton context - subsequent instantiations of the view model, or other view models, should yield a different DbContext.
Solution 1:[1]
You could employ custom lifetime scopes for that (https://autofac.readthedocs.io/en/latest/lifetime/working-with-scopes.html).
The idea is to register DbContext with InstancePerLifetimeScope() and then create a lifetime scope for every instance of view model. Autofac would create a single instance of DbContext per lifetime scope (and, thus, per view model).
The issue would be that custom lifetime scopes require manual disposal so you'd need to take care of LifetimeScope.Dipose() call after your view model is no longer needed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SzybkiDanny |
