小编Hen*_*sas的帖子

关于如何将Dapper与Structuremap和依赖注入一起使用的简单但很好的示例

我试图了解如何使用Dapper(IDbConnection)依赖注入,并仍然能够使用内置的dispose.

我在网上发现了一些文章,但我觉得很容易理解.

我想弄清楚的是如何使这个简单的类可测试:

public class UserProfileRepository : IUserProfileRepository
{
    private readonly IConfigRepository _configRepository;

    public UserProfileRepository(IConfigRepository configRepository)
    {
        _configRepository = configRepository;
    }

    public UserProfile GetUserProfile(string userId)
    {
        const string query = @"Select UserId, UserName
                                From Users
                                Where UserId = @UserId";

        using (var conn = new SqlConnection(_configRepository.GetConnectionString("MyConnectionString")))
        {
            conn.Open();
            return conn.Query<UserProfile>(query, new { UserId = userId }).SingleOrDefault();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个看起来像这样的配置库,所以我可以模拟对web.config的请求:

public class ConfigRepository : IConfigRepository
{
    public string GetConnectionString(string key)
    {
        var conString = ConfigurationManager.ConnectionStrings[key];
        if (conString != null)
        {
            return …
Run Code Online (Sandbox Code Playgroud)

c# structuremap dependency-injection dapper

6
推荐指数
1
解决办法
4016
查看次数

标签 统计

c# ×1

dapper ×1

dependency-injection ×1

structuremap ×1