c# - 使用什么是组合 Autofac 和 Dapper 的首选方式

标签 c# inversion-of-control ioc-container autofac dapper

我们一直在使用 EF 作为我们当前应用程序中大部分数据访问的主干,我们正在慢慢地从它转移到一些服务器密集型查询,并用 Dapper 取而代之。

考虑到这一点,实现与 Autofac 的连接的首选方法是什么?是注入(inject)一个IDBConnection还是一个连接字符串? IDBConnection 对我来说感觉更好,但如果您使用“使用”,它会被处理掉,后续调用无法访问它。

最佳答案

我们有同时使用 EF 和 Dapper 的项目。我们像这样注册 IDbConnection:

        builder.Register(c =>
            {
                var db = c.Resolve<MyDbContext>();
                if (db.Database.Connection.State != ConnectionState.Open)
                {
                    db.Database.Connection.Open();
                }
                return db.Database.Connection;
            })
               .As<IDbConnection>()
               .ExternallyOwned() // DbContext owns connection and closes him when disposing.
               .InstancePerHttpRequest();

并在我们的 Controller 中注入(inject) IDbConnection。

关于c# - 使用什么是组合 Autofac 和 Dapper 的首选方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12762733/

相关文章:

c# - 将占位符添加到密码 C# winforms 的文本框控件

C# 保存对象列表与保存对象(来自 JSON)

c# - 获取 "The entity type <model> is not part of the model for the current context."

c# - 运行时的 Autofac 绑定(bind)

c# - Ninject,多个服务绑定(bind)

c# - 如何在 C# 中将章节元数据嵌入到 mp3 文件中?

dependencies - Ninject/DI 在简单场景中有用吗?

java - spring中注入(inject)抽象类的问题

c# - 注入(inject)属性不适用于字段

inversion-of-control - 通过参数名称解​​决 CasSTLe Windsor 依赖关系