dimanche 9 août 2015

SQLite with Dapper in ASP MVC WEB API

I am working on simple project to use Dapper as ORM and SQLIte as db. I am wondering how to implement factory for IDbConnection. Now my code looks like below :

Controller class in web api :

  public IHttpActionResult PuttUser()
    {
        User user = new User()
        {
         [...]
        };
        DataBaseFactory.Connection.ExecuteNonQuery("...", user);
        return Ok(...);
    }

DataBaseFactory :

public static class DataBaseFactory
{
    private static string connectionString = "..."
    private static Lazy<IDbConnection> _connection = new Lazy<IDbConnection>(() => new SQLiteConnection(connectionString));


    public static IDbConnection Connection
    {
        get
        {
            return _connection.Value;
        }  
    }

}

DataBaseProvider

   public static class DataBaseProvider
    {
        public static void ExecuteNonQuery(this IDbConnection connection, string command, object param = null)
        {
            if (null == connection)
            {
                throw new NullReferenceException("Please provide a connection");
            }
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
            connection.Execute(command, param);
            connection.Close();
        }
    }

My Question :

Now every new query to my controller action will return static object for dbConnection. How it will be manage in memory of app when connection.close() will be invoked ? If connection property will be initialized ,how to removed this object after connection close ?

Aucun commentaire:

Enregistrer un commentaire