我試圖根據autofac實體指定要使用哪個dbcontext。下面是我的代碼:使用AutoFac選擇基於實體的DbContext
的Global.asax
foreach (var database in DatabaseManager.Databases)
{
builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString, database.Alias)) //database.Alias is database name
.As<IDbContext>()
.Named<IDbContext>(database.Alias)
.InstancePerLifetimeScope();
}
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
反正我有可以指定的DbContext傳遞給EfRepository?
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly IDbContext _context;
private IDbSet<T> _entities;
public EfRepository(IDbContext context)
{
this._context = context;
}
}
,並在我的實體,我將有這樣的事情
[DatabaseName("Database1")]
public partial class SampleEntity : BaseEntity
{
}
修訂 這裏是我的ObjectContext類
public class CodesObjectContext : DbContext, IDbContext
{
public virtual string DatabaseName { get; private set; }
public CodesObjectContext(string nameOrConnectionString, string databaseName)
: base(nameOrConnectionString)
{
DatabaseName = databaseName;
}
}
那麼,有沒有一種方法來匹配實體數據庫屬性和上下文數據庫名稱,然後僅將此上下文傳遞給存儲庫構造器
HI Mantas,我的問題與JSON –
無關[maybe] [https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/creating-custom-屬性)是你在找什麼? – Munzer
嗨Munzer,不。我想使用自定義屬性來指定哪個數據庫用於存儲庫中的上下文 –