autoFac-在多个存储库中使用相同的dbcontext

发布于 2025-01-27 17:51:33 字数 770 浏览 3 评论 0 原文

我有一个使用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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨后彩虹 2025-02-03 17:51:33

您可以使用自定义的寿命范围( 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文