有没有办法使用依赖注入我的连接一个简单的方法? [英] Is there a simple way to use Dependency Injection on my connections?

查看:284
本文介绍了有没有办法使用依赖注入我的连接一个简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来注入我连接到我的仓库。我试图注入的SqlConnection 使用的IDbConnection ,但我得到了一些问题,当 NInject 试图关闭连接,事件不会被调用。我无法弄清楚如何注入连接字符串到我的资料库。

I'm looking for a way to inject my connections into my repositories. I tried to inject the SqlConnection using the IDBConnection, but I got some problems when NInject tries to deactivate the connection, the event is never called. And I cannot figure out how to inject the connection string into my repositories.

有人能提供我一个建议?

Could someone provide me a suggestion?

推荐答案

我用NInject执行我的项目的依赖注入。

I use NInject to perform the Dependency Injection of my projects. I usually end with the configuration below:

简单工厂接口

public interface IDbConnectionFactory
{
    IDbConnection CreateConnection();
}

工厂实现

public class SqlConnectionFactory : IDbConnectionFactory
{
    private readonly string _connectionString;

    public SqlConnectionFactory(string connectionString)
    {
        _connectionString = connectionString;
    }

    public IDbConnection CreateConnection()
    {
        var conn = new SqlConnection(_connectionString);
        conn.Open();
        return conn;
    }
}

NInject配置:

NInject Config:

Bind<IDbConnectionFactory>()
    .To<SqlConnectionFactory>()
    .WithConstructorArgument("connectionString",
ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString);

一个仓库的例子:

Example of a repository:

public class UserRepository : IUserRepository
{
    private readonly IDbConnectionFactory _dbConnectionFactory;

    public UserRepository(IDbConnectionFactory dbConnectionFactory)
    {
        _dbConnectionFactory = dbConnectionFactory;
    }

    public IEnumerable<User> List()
    {
        using (var dbConnection = _dbConnectionFactory.CreateConnection())
        {
            ....
        }
    }
}

编辑:我总是让ADO.NET照顾连接池。于是我打开和关闭连接每一次,我需要执行数据库操作。

I always let the ADO.NET take care of connection pooling. So I open and close the connection every single time that I need to perform a database operation.

此方法为我工作,当你在你的问题中提到是非常简单的。

This approach is working for me and is very simple as you mentioned in your question.

这篇关于有没有办法使用依赖注入我的连接一个简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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