具有.NET Core的Dapper-注入的SqlConnection生命周期/作用域 [英] Dapper with .NET Core - injected SqlConnection lifetime/scope

查看:791
本文介绍了具有.NET Core的Dapper-注入的SqlConnection生命周期/作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET Core依赖注入在应用程序启动期间实例化SqlConnection对象,然后计划将其插入到存储库中. Dapper将使用此SqlConnection从我的存储库实现中的数据库读取/写入数据.我将在Dapper中使用async调用.

I'm using .NET Core Dependency Injection to instantiate a SqlConnection object during the application startup, which I'm then planning to inject in my repository. This SqlConnection will be used by Dapper to read/write data from the database within my repository implementation. I am going to use async calls with Dapper.

问题是:我应该以瞬态或单例形式注入SqlConnection吗?考虑到我想使用async的事实,除非Dapper在内部实现了一些隔离容器,否则我的想法是使用瞬态,并且我的单例的作用域仍将包装在Dapper内部使用的任何作用域中.

The question is: should I inject the SqlConnection as transient or as a singleton? Considering the fact that I want to use async my thought would be to use transient unless Dapper implements some isolation containers internally and my singleton's scope will still be wrapped within whatever the scope Dapper uses internally.

在使用Dapper时,是否有关于SqlConnection对象的生存期的任何建议/最佳实践?我可能会缺少一些警告吗?

Are there any recommendations/best practices regarding the lifetime of the SqlConnection object when working with Dapper? Are there any caveats I might be missing?

谢谢.

推荐答案

如果您以单例形式提供SQL连接,则除非启用MARS,否则将无法同时处理多个请求,这也有其局限性.最佳做法是使用临时SQL连接并确保正确处理它.

If you provide SQL connection as singleton you won't be able to serve multiple requests at the same time unless you enable MARS, which also has it's limitations. Best practice is to use transient SQL connection and ensure it is properly disposed.

在我的应用程序中,我将自定义IDbConnectionFactory传递给存储库,该存储库用于在using语句内创建连接.在这种情况下,存储库本身可以是单例的,以减少堆上的分配.

In my applications I pass custom IDbConnectionFactory to repositories which is used to create connection inside using statement. In this case repository itself can be singleton to reduce allocations on heap.

这篇关于具有.NET Core的Dapper-注入的SqlConnection生命周期/作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆