如何在运行时解析服务中的命名OrmLiteConnectionFactory?

时间:2014-09-09 04:36:06

标签: ormlite-servicestack

我在apphost中创建了一个OrmLiteConnectionFactory,并添加了2个命名连接," ConnOne"和" ConnTwo"通过RegisterConnection。我希望使用基于服务中的属性的任何一个可互换,直到运行时才能解析。

var factory = new OrmLiteConnectionFactory();
        factory.RegisterConnection("ConnOne", Config.SqlServerTenantOne, SqlServerDialect.Provider);
        factory.RegisterConnection("ConnTwo", Config.SqlServerTenantTwo, SqlServerDialect.Provider);



public class Repository : IDisposable {

    public string Tenant { get; set; }

    public IDbConnectionFactory DbFactory { get; set; } //not injected

    IDbConnection db;
    IDbConnection Db 
    { 
        get 
        {
            return db ?? db = DbFactory.OpenDbConnection(Tenant); //DbFactory is null
        }
    }

    public List<Todo> GetByIds(long[] ids)
    {
        return Db.Ids<Todo>(ids);
    }

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

但是当我运行它时,DbFactory总是为空。什么是解决这个问题的最好方法?

谢谢你, 斯蒂芬

1 个答案:

答案 0 :(得分:0)

需要协调三个项目:

1)更改工厂的签名,在使用OrmLiteConnectionFactory无参数构造函数之前设置DialectProvider非常重要。

OrmLiteConfig.DialectProvider = PostgreSQLDialectProvider.Instance;

var dbFactory = new OrmLiteConnectionFactory();

dbFactory.RegisterConnection("NamedKeyConnOne", 
                         new OrmLiteConnectionFactory(Config.TenantOne));
dbFactory.RegisterConnection("NamedKeyConnTwo", 
                         new OrmLiteConnectionFactory(Config.TenantTwo));

2)注册工厂

container.Register<IDbConnectionFactory>(dbFactory);

3)使用OpenDbConnection方法并传入&#34; NamedKey&#34;,这将返回正确的连接。

public abstract partial class BorrowerRepository : IDisposable
{
    private IDbConnection _db;

    /// <summary>
    /// This should be set to the string - Tenant
    /// </summary>
    public string TenantKey { get; set; }

    public IDbConnectionFactory DbFactory { get; set; }

    public IDbConnection Db
    {
        get
        {
            if (String.IsNullOrEmpty(TenantKey))
            {
                throw new ArgumentException("The TenantKey property has to be set before using the DbFactory.");
            }
            return _db ?? (_db = DbFactory.OpenDbConnection(TenantKey));
        }
    }

    public virtual void Dispose()
    {
        if (_db == null)
            return;
        _db.Dispose();
    }
}