freesql多库访问

顾名思义,因为需要访问到两个数据库,一个日志库,一个业务库。之前开发都是用ado.net链接,最近使用freesql这个orm,就需要改动一下了。之前使用到freesql都是链接一个数据库就ok,现在数据库分开了,那就有了这么个需求。

首先引用IdleBus

ps:具体的使用说明可以参考IdleBus 空闲对象管理容器 - .NET开发社区 | CTOLib码库

新建一个DbBus类

public enum DbName { db0, db1 }
public class DbBus : IdleBus<DbName, IFreeSql>
{
    public DbBus() : base(TimeSpan.FromMinutes(30)) { }
}

超过30秒没有使用就销毁实例

使用的是.net core 所以在Startup.cs里注册一下。我对这个注册还不是很熟,功能实现了就把使用记录下来了。如果有哪位大神指导一下我的错误,会非常感谢。

static DbBus ib = new DbBus();
public Startup(IConfiguration configuration)
{
    ib.Register(DbName.db0, () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, @"Server=;Database=Logs;Uid=;Pwd=;").Build());
    ib.Register(DbName.db1, () => new FreeSqlBuilder().UseConnectionString(DataType.SqlServer, @"Server=;Database=Busi;Uid=;Pwd=;").Build());
    Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(ib);//使用的时候用 Get 方法,不要存其引用关系
    services.AddControllersWithViews();
}

在controller里这么添加进来

IFreeSql _fsqlUser;
IFreeSql _fsql;
public ProfileController(DbBus ib)
{
    _fsqlUser = ib.Get(DbName.db1); 
    _fsql = ib.Get(DbName.db0);
}

在下面的action方法里就可以使用了。

_fsql.Select<T>().Limit(10).ToList();
原文地址:https://www.cnblogs.com/Lvkang/p/14626395.html