Я нашел решение, позволяющее использовать две базы данных, и где вы можете решить для каждой сущности, какую базу данных использовать:
Global.asax
private static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.DefaultControlledBy<HttpRequestLifecycle>();
SessionFacade.DatabaseSessionFactories[DbConnectionSessionType.MsqlSession] = NHConfiguration.CreateSessionFactory();
SessionFacade.DatabaseSessionFactories[DbConnectionSessionType.PostgresqlSession] = NHConfiguration.CreatePostgresSessionFactory();
builder.Register(c => c.ResolveAll<IDatabaseSessions>()).ControlledBy<HttpRequestLifecycle>();
LightCoreConfiguration.RegisterGlobalDependencies(builder);
// Build the container.
_container = builder.Build();
}
protected void Application_EndRequest(object sender, EventArgs e)
{
var sessions = _container.Resolve<IDatabaseSessions>();
sessions.MssqlSession.Close();
sessions.MssqlSession.Dispose();
sessions.PostgresqlSession.Close();
sessions.PostgresqlSession.Dispose();
}
SessionFacade.cs
public static class SessionFacade
{
/// <summary>
/// Gets the database connection string.
/// </summary>
public static string DatabaseConnectionString => Environment.GetEnvironmentVariable("Database:Connection");
public static string DatabasePostgresConnectionString => Environment.GetEnvironmentVariable("DatabasePostgres:Connection");
public static Dictionary<DbConnectionSessionType, ISessionFactory> DatabaseSessionFactories
{
set; get;
} = new Dictionary<DbConnectionSessionType, ISessionFactory>() {
{
DbConnectionSessionType.MsqlSession,
null
},
{
DbConnectionSessionType.PostgresqlSession,
null
}
};
}
IDatabaseSessions
public interface IDatabaseSessions
{
ISession MssqlSession { get; set; }
ISession PostgresqlSession { get; set; }
}
LightCoreConfiguration
public static class LightCoreConfiguration
{
public static void RegisterGlobalDependencies(ContainerBuilder builder)
{
builder.Register<IDatabaseSessions, DatabaseSessions>();
}
}
}
DatabaseSessions
public class DatabaseSessions: IDatabaseSessions
{
public DatabaseSessions()
{
MssqlSession = SessionFacade.DatabaseSessionFactories[DbConnectionSessionType.MsqlSession].OpenSession();
PostgresqlSession = SessionFacade.DatabaseSessionFactories[DbConnectionSessionType.PostgresqlSession].OpenSession();
}
public ISession MssqlSession { get; set; }
public ISession PostgresqlSession { get; set; }
}
Repository.cs
public class Repository<T> : IRepository<T> where T : Entity
{
public Repository(IDatabaseSessions databaseSessions, DbConnectionSessionType connectionType = DbConnectionSessionType.PostgresqlSession)
{
if(connectionType == DbConnectionSessionType.MsqlSession) _session = databaseSessions.MssqlSession;
if(connectionType == DbConnectionSessionType.PostgresqlSession) _session = databaseSessions.PostgresqlSession;
}
}
}
Наконец служба
public class UserService
{
public UserService(IDatabaseSessions databaseSessions) : base(new Repository<User>(databaseSessions))
{
}
}