I'm developing an N-Tier web application which uses a database for each client with Simple Injector for IoC and generic repository pattern.
When I tried to change the db connection I found that the injector runs in Application_Start in Glopal.asax where I still can't figure out who is the current user to set the connection string, I need to change it in the runtime not in the Application_Start, any ideas?
Sample of my Repository Class
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private readonly IDBContext _context;
private IDbSet<T> _entities;
public Repository(IDBContext context)
{
_context = context;
}
private IDbSet<T> Entities
{
get
{
if (_entities == null)
{
_entities = _context.Set<T>();
}
return _entities;
}
}
}
Sample of DBContxt Class
public class DBContext: DbContext, IDBContext
{
public DBContext()
: base("Name=DbConnectionString")
{
Database.SetInitializer<DBContext>(null);
}
//public DBContext(ConnectionStr connection)
// : base(connection.conn)
//{
// Database.SetInitializer<DBContext>(null);
//}
public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
{
return base.Set<TEntity>();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(
type =>
type.BaseType != null && type.BaseType.IsGenericType &&
type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
}