Search code examples
postgresqlormlite-servicestack

ServiceStack OrmLite and PostgreSQL - timeouts


I am updating large amounts of data using ServiceStack's OrmLite with a connection to PostgreSQL, however, I am getting a large amount of timeouts.

Sample Code:

public class AccountService : Service
{
    public object Any(ImportAccounts request)
    {
        var sourceAccountService = this.ResolveService<SourceAccountService();
        var sourceAccounts = (GetSourceAccountResponse)sourceAccountService.Get(new GetSourceAccounts());

        foreach (var a in sourceAccounts)
        {
            Db.Save(a.ConvertTo<Account>());
        }


    }
}

The Source Account service, which sits in the same project & accesses the same Db.

public class SourceAccountService : Service
    {
        public object Get(GetSourceAccounts request)
        {
           return new GetSourceAccountsResponse { Result = Db.Select<SourceAccounts>().ToList() };
        }
    }

Questions,

  1. Should I be expecting large amount of timeouts considering the above set up?

  2. is it better to be using using (IDbConnection db = DbFactory.OpenDbConnection()) instead of Db?


Solution

  • If you're resolving and executing a Service you should do it in a using statement so its open Db connection and other resources are properly disposed of:

    using (var service = this.ResolveService<SourceAccountService())
    {
        var sourceAccounts = service.Get(new GetSourceAccounts());
        foreach (var a in sourceAccounts)
        {
            Db.Save(a.ConvertTo<Account>());
        }
    }
    

    If you're executing other Services it's better to specify the Return type on the Service for added type safety and reduced boiler plate at each call site, e.g:

    public class SourceAccountService : Service
    {
        public GetSourceAccountsResponse Get(GetSourceAccounts request)
        {
            return new GetSourceAccountsResponse { 
                Result = Db.Select<SourceAccounts>()
            };
        }
    }
    

    Note: Db.Select<T> returns a List so .ToList() is unnecessary,

    Another alternative for executing a Service instead of ResolveService<T> is to use:

    var sourceAccounts = (GetSourceAccountsResponse)base.ExecuteRequest(new GetSourceAccounts());
    

    Which is same above and executes the Service within a using {}.