Search code examples
c#asp.netentity-frameworkormlite-servicestack

Owin with custom ORM framework (not Entity Framework)


I was recently using Entity framework together with Identity and OWIN but no I no longer want to use Entity and instead use OrmLite from ServiceStack.

The problem I'm facing right now is I don't quite understand how to replace this part from Owin startup class:

`app.CreatePerOwinContext(AppDbContext.Create);
 app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);

to use OrmLite. How should I do this?

Just create a method that returns an OrmLiteFactory? Altough OrmLiteFactory does not implement IDisposable and will not work


Solution

  • The OrmLiteConnectionFactory should be registered as a singleton. You can then use it to create ADO.NET IDbConnection with:

    using (var db = dbFactory.OpenDbConnection())
    {
        //
    }
    

    Once it's registered as a Singleton you could use a lazy property pattern that's like in the RepositoryBase class to simplify data access, e.g:

    public abstract class RepositoryBase : IDisposable, IRepository
    {
        public virtual IDbConnectionFactory DbFactory { get; set; }
    
        IDbConnection db;
        public virtual IDbConnection Db
        {
            get { return db ?? (db = DbFactory.OpenDbConnection()); }
        }
    
        public virtual void Dispose()
        {
            if (db != null)
                db.Dispose();
        }
    }
    

    This will let access the Db connection like a normal connection and since it's IDisposable should dispose it after the request is executed, e.g:

    public class MyController : RepositoryBase
    {
        public List<Poco> GetPocos()
        {
            return Db.Select<Poco>();
        }
    }