如何结合dapper和asp.net核心身份

时间:2017-05-31 13:29:59

标签: c# mysql asp.net-core dapper asp.net-core-identity

我正在尝试将Dapper和MySqlConnector用于MySql数据库和.net核心身份。 我遵循了这个文档: https://docs.microsoft.com/en-us/aspnet/identity/overview/extensibility/overview-of-custom-storage-providers-for-aspnet-identity让它运作起来。但它是.net而不是.net核心(有区别吗?)。无论如何,现在我尝试在Startup.cs中获取数据库连接的连接字符串,不知怎的,我不得不说使用此连接的身份,但我不知道如何!我创建了所有必要的类,如userTables,RoleTable,UserStores,RoleStores等等。但我想我的问题是,这两个类是相关的。

My Startup.cs:

public void ConfigureServices(IServiceCollection services)
{

    services.Configure<MySQLDatabase>(Configuration.GetSection("DapperConnection"));


    services.AddIdentity<ApplicationUser, ApplicationUserRole>()

        .Add <=== here was the EntityFrameworkStores what  have i to add, so identity knows about the connection?

        .AddDefaultTokenProviders();


    services.AddMvc();

    //Add application services
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();

}

MySQLDatabase.cs

using System;
using System.Collections.Generic;
using IdentityServer.Data.Abstract;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data;
using System.Threading;

namespace IdentityServer.Data.Concrete
{
    // Class that encapsulates a MySQL databse connections and CRUD operations

    public class MySQLDatabase : IDisposable
    {


        private MySqlConnection _connection;

        // Dwfault constructor which uses the "DefaultConnection" connectionString

        public MySQLDatabase()
            : this("DefaultConnection")
        {
        }

        // Constructor which takes the connction string name

        public MySQLDatabase(string connectionStringName)
        {
            string connectionsString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
            _connection = new MySqlConnection(connectionsString);
        }

        //Executes a non-query MySQL statement

        public int Execute(string commandText, Dictionary<string, object> parameters)
        {
            int result = 0;

            if (String.IsNullOrEmpty(commandText))
            {
                throw new ArgumentException("Command text cannot be null or empty.");
            }

            try
            {
                EnsureConnectionOpen();
                var command = CreateCommand(commandText, parameters);
                result = command.ExecuteNonQuery();
            }
            finally
            {
                _connection.Close();
            }
            return result;
        }

        // Executes a MYSQL query that returns a single scalar value as the result.

        public object QueryValue(string commandText, Dictionary<string, object> parameters)
        {
            object result = null;

            if (String.IsNullOrEmpty(commandText))
            {
                throw new ArgumentException("Command text connot be null or empty.");
            }

            try
            {
                EnsureConnectionOpen();
                var command = CreateCommand(commandText, parameters);
                result = command.ExecuteScalar();
            }
            finally
            {
                EnsecureConnectionClosed();
            }

            return result;
        }

        // Executes a SQL query that returns a list of rows as the result

        public List<Dictionary<string, string>> Query(string commandText, Dictionary<string, object> parameters)
        {
            List<Dictionary<string, string>> rows = null;
            if (String.IsNullOrEmpty(commandText))
            {
                throw new ArgumentException("Command text cannot be null or empty.");
            }

            try
            {
                EnsureConnectionOpen();
                var command = CreateCommand(commandText, parameters);
                using (MySqlDataReader reader = command.ExecuteReader() as MySqlDataReader)
                {
                    rows = new List<Dictionary<string, string>>();
                    while (reader.Read())
                    {
                        var row = new Dictionary<string, string>();
                        for (var i = 0; i < reader.FieldCount; i++ )
                        {
                            var columnName = reader.GetName(i);
                            var columnValue = reader.IsDBNull(i) ? null : reader.GetString(i);
                            row.Add(columnName, columnValue);
                        }
                        rows.Add(row);
                    }
                }

            }
            finally
            {
                EnsecureConnectionClosed();
            }
            return rows;
        }

        //Opens a connection if not open

        private void EnsureConnectionOpen()
        {
            var retries = 3;
            if (_connection.State == ConnectionState.Open)
            {
                return;
            }
            else
            {
                while (retries >= 0 && _connection.State != ConnectionState.Open)
                {
                    _connection.Open();
                    retries--;
                    Thread.Sleep(30);
                }
            }
        }

        //Closes a connection if open

        public void EnsecureConnectionClosed()
        {
            if (_connection.State == ConnectionState.Open)
            {
                _connection.Close();
            }
        }

        //Creates a MysqlCommand with the given parameters

        private MySqlCommand CreateCommand(string commandText, Dictionary<string, object> parameters)
        {
            MySqlCommand command = new MySqlCommand(commandText, _connection);// _connection.CreateCommand();
            //command.CommandText = commandText;
            AddParameters(command, parameters);

            return command;
        }

        //Adds the paramters to a MySql command

        private static void AddParameters(MySqlCommand command, Dictionary<string, object> parameters)
        {
            if (parameters == null)
            {
                return;
            }

            foreach (var param in parameters)
            {
                var parameter = command.CreateParameter();
                parameter.ParameterName = param.Key;
                parameter.Value = param.Value ?? DBNull.Value;
                command.Parameters.Add(parameter);
            }
        }

        //Helper method to return query a string value

        public string GetStrValue(string commandText, Dictionary<string, object> parameters)
        {
            string value = QueryValue(commandText, parameters) as string;
            return value;
        }

        public void Dispose()
        {
            if (_connection != null)
            {
                _connection.Dispose();
                _connection = null;
            }
        }
    }
}

0 个答案:

没有答案