使用AutoFac选择基于实体的DbContext

时间:2017-06-05 03:20:58

标签: c# entity-framework autofac

我试图根据具有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;
        }            
}

有没有办法匹配实体数据库属性和上下文数据库名称,然后只将此上下文传递给存储库构造函数

1 个答案:

答案 0 :(得分:0)

假设您已经定义了属性DatabaseName,我将回答

//first in your base context, define contructor that takes string as database name.
//It should be something like this 
public MyContext(string mydbName = "DefaultDBName") : base(mydbName)
        {
        }

// In your getter, do something like this, get database Name from your attributes  
string dbName =
            (DatabaseName) Attribute.GetCustomAttribute(typeof(T), typeof (DatabaseName));
if(dbName==null) throw new Exception ("Missing Attribute");
else
{
// .Name might change depending on your attribute
string DatabaseName = db.Name;
// then init your context 
    using (var db = new MyContext(DatabaseName))
    {//do something }
}

我希望这会有所帮助。