[英]EF Switch between different contexts of same type
我有一個mulitenant應用程序,該應用程序具有多個數據庫,用於具有相同數據庫結構的不同客戶。
在應用程序中,用戶根據其客戶ID登錄后,我將知道其客戶數據庫的連接字符串,並且在他的登錄按鈕單擊事件之后,我需要動態地動態更改數據庫上下文。
我正在使用EF 5.0和Autofac IOC容器。 我在這里粘貼了我的代碼,這對我沒有幫助。
什么是最好的管理方式?
string EntityFrameworkConnectionString = null;
var builder = new ContainerBuilder();
builder.Register(c =>
{
if (string.IsNullOrEmpty(EntityFrameworkConnectionString))
{
var profileProvider = c.Resolve<IConfigurationProfileProvider<CustomerProfile>>();
var profile = profileProvider.GetProfile();
EntityFrameworkConnectionString = profile.CustomerDatabaseConnectionString;
}
return new CustomerDataContext(EntityFrameworkConnectionString);
})
.As<ICustomerDataContext>()
.As<IDbContext>()
.InstancePerDependency();
builder.RegisterType<CustomerDataContextFactory>().As<ICustomerDataContextFactory>();
var assembly = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.InstancePerDependency();
我會這樣:
介紹一個將管理連接字符串的接口:
public interface IConnectionStringManager { string GetConnectionString(); }
通過將IConfigurationProfileProvider注入其中的實現:
public class ConnectionStringManager : IConnectionStringManager { private readonly IConfigurationProfileProvider<CustomerProfile> _configurationProfileProvider; public ConnectionStringManager(IConfigurationProfileProvider<CustomerProfile> configurationProfileProvider) { _configurationProfileProvider = configurationProfileProvider; } public string GetConnectionString() { return _configurationProfileProvider.GetProfile().CustomerDatabaseConnectionString; } }
然后將IConnectionStringManager注入CustomerDataContext並獲取連接字符串。
public CustomerDataContext(IConnectionStringManager connectionStringManager) { var connectionString = connectionStringManager.GetConnectionString(); // pass the connectionString to your context }
並照常注冊ConnectionStringManager和CustomerDataContext:
builder.RegisterType<ConnectionStringManager>().As<IConnectionStringManager>(); builder.RegisterType<CustomerDataContext>() .As<ICustomerDataContext>() .As<IDbContext>() .InstancePerDependency();
順便說一句,請看一下可以簡化多租戶支持的Autofac多租戶集成 。
我真的不認為您需要在這種情況下使用IOC(尤其是考慮到制作過程的復雜程度)。 為什么不只是將連接字符串存儲為靜態變量,然后重寫DbContext
的構造函數以始終使用該變量呢?
像這樣:
對於連接字符串:
public static class StaticVariables
{
public static string ConnectionString { get; set; }
}
對於您的DbContext
構造函數:
public DbContext()
{
this(StaticVariables.ConnectionString);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.