为了回答我自己的问题,我最终为要连接的每个数据库创建了一个自定义 DocumentStore 和 ISessionFactory,然后注入了自定义 SessionFactory。
这是代码(为简洁起见,仅显示每个类的一个实例。只需替换Db1为Db2每个类的第二个版本):
自定义 DocumentStore:
public class Db1Store : DocumentStore
{
public Db1Store(StoreOptions options) : base(options)
{
}
}
自定义 SessionFactory:
public class Db1SessionFactory : ISessionFactory
{
private readonly Db1Store store;
public Db1SessionFactory(Db1Store store)
{
this.store = store;
}
public IQuerySession QuerySession()
{
return store.QuerySession();
}
public IDocumentSession OpenSession()
{
return store.OpenSession();
}
}
服务注册(这取代了services.AddMarten调用):
services.AddSingleton(p =>
{
var options = new StoreOptions();
options.Connection(configuration.GetConnectionString("DB1"));
options.AutoCreateSchemaObjects = AutoCreate.All;
options.Serializer(new JsonNetSerializer { EnumStorage = EnumStorage.AsString });
return new Db1Store(options);
});
services.AddSingleton<Db1SessionFactory>();
然后将 Db1SessionFactory 实例注入到您的类中,并运行如下查询:
var result = await db1SessionFactory.QuerySession().Query<MyAwesomeTable>().ToListAsync();
缺点: