A simple but good example of how to use Dapper with Structuremap and dependency

I'm trying to figure out how to use Injection Dependency with Dapper (IDbConnection) and still use the built-in utility.

I found a couple of articles on the Internet, but I don’t think it’s easy to understand.

I am trying to figure out how to make this simple class available for testing:

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();
        }
    }
}

I have a configuration repository that looks like this, so I can make fun of the request for web.config:

public class ConfigRepository : IConfigRepository
{
    public string GetConnectionString(string key)
    {
        var conString = ConfigurationManager.ConnectionStrings[key];
        if (conString != null)
        {
            return conString.ConnectionString;
        }

        return string.Empty;
    }
}

I read that you can use ConnectionFactory, but you don’t know how to implement it, and yet you know that I am disposing correctly.

Can someone point me in the right direction?

+4
1

DependencyInjection ConnectionFactory. IConfigRepository, factory

: Multi fold:

  • , , ( Connection Factory)

( ):

IDBConnection :

[Inject] // Property Injection
public IDBConnection Connection {get; set;}

DI, Ninject:

Bind<IDBConnection>().ToMethod(ctx => 
ConnectionFactory.CreateDbConnection("DefaultConnection"));

DBConnection Factory :

Factory :

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=<Value>;Initial Catalog=<Value>;User Id=<Value>;Password=<Value>" providerName="System.Data.SqlClient" />
</connectionStrings>

DefaultConnection, SqlClient, , Oracle, MySql

 using System;
 using System.Data.Common;

 public static class ConnectionFactory
    {
        /// <summary>
        /// Create DBConnection type based on provider name and connection string
        /// </summary>
        /// <param name="connectionIdentifier"></param>
        /// <returns></returns>
        public static DbConnection CreateDbConnection(string connectionIdentifier)
        {
            // Provider name setting
            var providerNameValue = ConfigurationManager.ConnectionStrings[connectionIdentifier].ProviderName;

            // Connection string setting
            var connectionStringValue = ConfigurationManager.ConnectionStrings[connectionIdentifier].ConnectionString;

            // Assume failure.
            DbConnection connection;

            // Null connection string cannot be accepted
            if (connectionStringValue == null) return null;

            // Create the DbProviderFactory and DbConnection.
            try
            {
                // Fetch provider factory
                var factory = DbProviderFactories.GetFactory(providerNameValue);

                // Create Connection
                connection = factory.CreateConnection();

                // Assign connection string
                if (connection != null)
                    connection.ConnectionString = connectionStringValue;
            }
            catch (Exception ex)
            {
                connection = null;
            }
            // Return the connection.
            return connection;
        }
}

:

using(Connection)
{
 ...
}

as-is, no using required

Mocking:

Mock , UserProfileRepository :: GetUserProfile(string userId), MockConnection Injection, . DI ,

0

Source: https://habr.com/ru/post/1659109/


All Articles