2015-05-27 32 views
1

我對使用實體框架使用Code First Migrations進行編碼。我正在使用一個自定義的構造函數,該構造函數具有特定於應用程序中登錄的某個用戶的連接字符串。使用自定義構造函數進行代碼優先遷移

當應用程序加載時,如果數據庫上下文有任何更改,我想用用戶連接字符串初始化數據庫並將其遷移到最新版本。我正在使用結構圖來注入工作單元。

全球ASAX

ObjectFactory.Configure(cfg => 
     { 
      cfg.AddRegistry(new StandardRegistry()); 
      cfg.AddRegistry(new ControllerRegistry()); 
      cfg.AddRegistry(new ActionFilterRegistry(() => Container ?? ObjectFactory.Container)); 
      cfg.AddRegistry(new MvcRegistry()); 
      cfg.AddRegistry(new TaskRegistry()); 
      cfg.AddRegistry(new ModelMetadataRegistry()); 
     }); 

StandardRegistry類

For<ICustomerUnitOfWork>().Use(new CustomerUnitOfWork(new CustomerContext())); 
     For<CustomerContext>().Use(new CustomerContext()); 

在這一點上我不當知道用戶的ConnectionString因爲用戶沒有登錄。問題模型已經改變,結構圖會引發異常,因爲上下文模型已經改變。

語境

private static string _connectionString; 

    static CustomerContext() 
    { 
     Database.SetInitializer(new MigrateDatabaseToLatestVersion<CustomerContext, Configuration>()); 
    } 

    public CustomerContext() 
     : base(string.IsNullOrEmpty(_connectionString) ? "FooDatabase" : _connectionString) 
    { 
     if (string.IsNullOrEmpty(_connectionString)) 
      Database.SetInitializer(new CustomerContextInitializer()); 
    } 


    public CustomerContext(string connectionString) 
     : base(connectionString) 
    { 
     if (string.IsNullOrEmpty(_connectionString)) 
      Database.SetInitializer(new CustomerContextInitializer()); 
     _connectionString = connectionString; 
    } 

CustomerContextInitializer

public class CustomerContextInitializer : CreateDatabaseIfNotExists<CustomerContext> 
{ 
    protected override void Seed(CustomerContext context) 
    { 
     var informationService = new InformationService 
     { 
      ObjectState = ObjectState.Added, 
      ConnectorClass = 
       "Conexio.InformationService.Contracts.IInformationService, Conexio.InformationService.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", 
      DisplayName = "IInformationService" 
     }; 

是有辦法的規則添加到standardRegistry類運行時調用與ConnectionString中constructur?還是有另一種方法來解決這個問題?

回答

0

如果我正確理解你的問題,解決這個你最好的方法是通過創建一個工廠類,是負責在運行時,然後可以在你的StructureMap註冊表中配置像這樣創建的ICustomerUnitOfWork實例:

this.For<ICustomerUnitOfWork>().Use(ctx => ctx.GetInstance<YourFactoryClass>().ResolveCustomerUnitOfWork()); 

然後,您的ICustomerUnitOfWork將解析爲您的工廠類,該工廠類可以注入其自己的一組依賴項,以確定正確的上下文是什麼。

public interface ICustomerUnitOfWork 
{ 

} 

public class YourFactoryClass 
{ 
    public YourFactoryClass(string connectionString) 
    { 

    } 

    public ICustomerUnitOfWork ResolveCustomerUnitOfWork() 
    { 
     // Perform runtime configuration 

     return unitOfWork; 
    } 
} 

我希望這有助於!