[英]How to use EF sharing same DbContext for multiple databases
我有一個多租戶應用程序,它使用具有多個客戶數據庫的同一個Web應用程序並共享了DbContext。 當用戶基於其憑據登錄時,我將提供連接字符串到DbContext並加載數據。 當多個用戶同時登錄並且隨着DbContext不斷在不同用戶之間切換而可以看到彼此的數據時,會發生問題。
我主要使用EF 5.0和Autofac IOC。 什么是最好的管理方式?
如何讓我的DbContext維護該特定用戶的數據,並且即使其他用戶登錄並且它們具有不同的數據庫上下文,它們也不會更改?
這是我的登錄頁面中的代碼,
protected void LoginBtn_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(CustomerId.Text);
var builder = new ContainerBuilder();
var profile = _profileProvider.GetCustomerProfile(i);
ConnectionStringManager.ConnectionString = profile.connString;
builder.RegisterModule<CustomerDataModule>();
builder.Update(_container);
Response.Redirect("Home.aspx");
}
這是我的靜態變量,它提供連接字符串
public static class ConnectionStringManager
{
public static string ConnectionString { get; set; }
}
這是我的模塊,其中包含所有實體和上下文類,
public class CustomerDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.Register(c =>
{
ConnectionString = ConnectionStringManager.ConnectionString;
return new CustomerDataContext(ConnectionString);
})
.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();
}
}
這是我的DbContext,
public partial class CustomerDataContext: DbContext, ICustomerDataContext
{
public CustomerDataContext(string connectionString)
: base(connectionString)
{ }
.......
這是我的資料庫之一
public class CustomerRepository : GenericRepository<Customer, int>, ICustomerRepository
{
public CustomerRepository(ICustomerDataContext context)
: base(context, customer => customer.Id)
{
}
}
Web應用程序中的靜態變量意味着同時在所有用戶之間共享其數據。 您需要將該值移動到特定於每個用戶的會話變量。
var builder = new ContainerBuilder();
// will add `HTTP request lifetime scoped` registrations (InstancePerHttpRequest) for the HTTP abstraction classes
builder.RegisterModule(new AutofacWebTypesModule());
builder.Register<MyType>(ctx =>
{
var sessionBase = ctx.Resolve<HttpSessionStateBase>();
//now use the session value to retrieve the connection string
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.