【问题标题】:Selecting DbContext based on Entity with AutoFac使用 AutoFac 选择基于实体的 DbContext
【发布时间】:2017-06-05 15:13:31
【问题描述】:

我正在尝试根据具有 autofac 的实体指定要使用的 dbcontext。以下是我的代码:

全球.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 无关
  • 也许 this 是你要找的?
  • 嗨,Munzer,不。我想使用自定义属性来指定用于存储库中上下文的数据库

标签: c# entity-framework autofac


【解决方案1】:

假设您已经定义了属性 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 }
}

我希望这会有所帮助。

【讨论】:

  • 我已经更新了这个问题。我认为您错过了范围内的 autofac
  • 我不确定什么是autofac,在阅读更新后,我仍然认为答案不需要更改,除非您还没有创建DatabaseName注解。
猜你喜欢
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
相关资源
最近更新 更多