我有一个使用AutoFac的桌面应用程序。我使用的框架不提供依赖注入的钩子,因此使用服务定位器模式实例化视图模型。
我的一个视图模型有两个存储库。存储库都采用一个对象,IS是应用程序 dbContext
。
AutoFac实例化两个 dbContext
实例 - 每个存储库一个。两个存储库应使用相同的 dbContext
实例。
服务定位器的实现为:
ServiceLocator.Current = new ServiceLocator((type) =>
{
var resolved = _container.Resolve(type);
return resolved;
});
其中 _container
是 icontainer
y构建的实例:
var builder = new ContainerBuilder();
/* snip */
_container = builder.Build();
我如何让AutoFac使用相同的 dbcontext
在所有依赖关系中创建视图模型的实例?
我肯定不想要单身顿上下文 - 随后的视图模型的实例化或其他视图模型,应产生不同的 dbContext
。
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
.
发布评论
评论(1)
您可以使用自定义的寿命范围( dbContext 注册
instanceperlifetimescope()
,然后为查看模型的每个实例创建寿命范围。 AUTOFAC将创建一个dbContext
的单个实例,每个生命周期范围(因此,每个视图模型)。问题是自定义寿命范围需要手动处理,因此您需要照顾
lifetimesscope.dipose()
不再需要查看模型后调用。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
withInstancePerLifetimeScope()
and then create a lifetime scope for every instance of view model. Autofac would create a single instance ofDbContext
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.