2017-06-05 69 views
0

我試圖根據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; 
     }    
} 

那麼,有沒有一種方法來匹配實體數據庫屬性和上下文數據庫名稱,然後僅將此上下文傳遞給存儲庫構造器

+0

HI Mantas,我的問題與JSON –

+0

無關[maybe] [https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/creating-custom-屬性)是你在找什麼? – Munzer

+0

嗨Munzer,不。我想使用自定義屬性來指定哪個數據庫用於存儲庫中的上下文 –

回答

0

假設你已經確定你的屬性數據庫名,我會回答

//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 } 
} 

我希望這將有助於。

+0

我已經更新了這個問題。我想你錯過了範圍 –

+0

autofac我不知道什麼是autofac,在閱讀更新後,我仍然認爲答案不需要改變,除非你還沒有創建你的DatabaseName註釋。 – Munzer