2009-08-15 69 views
5

如何在StructureMap注册构造函数中获取某种类型的实例(在不同的注册表中注册)?我想要使​​用这样的代码:如何在StructureMap注册构造函数中获取实例?

public RepositoriesRegistry() 
    { 
     IApplicationSettings lApplicationSettings = 
      ObjectFactory.GetInstance<IApplicationSettings>(); 
     Debug.Assert(lApplicationSettings != null); 

     const string cSupportedDevicesConnectionString = 
      "metadata=res://*/Models.SupportedDevices.Database.SupportedDevicesModel.csdl|res://*/Models.SupportedDevices.Database.SupportedDevicesModel.ssdl|res://*/Models.SupportedDevices.Database.SupportedDevicesModel.msl;provider=System.Data.SqlClient;provider connection string=\"{0}\""; 
     string lSupportedDevicesConnectionString = 
      string.Format(cSupportedDevicesConnectionString, lDatabaseConnectionString); 
     SupportedDevicesEntities lSupportedDevicesEntities = 
      new SupportedDevicesEntities(lSupportedDevicesConnectionString); 
     ForRequestedType<SupportedDevicesEntities>().TheDefault.IsThis(
      lSupportedDevicesEntities); 
     ForRequestedType<ISupportedDevicesRepository>().TheDefault.IsThis(
      new SupportedDevicesRepository(lSupportedDevicesEntities)); 

    } 

IApplicationSettings是应用程序设置的接口。实现此接口(目前ConfigFileApplicationSettings类)的具体类型注册在另一个注册表这样的:

public ApplicationServicesRegistry() 
    { 
     ForRequestedType<IApplicationSettings>().TheDefault.IsThis(
      new ConfigFileApplicationSettings()); 
    } 

而且两者登记在引导程序注册:

 #region IBootstrapper Members 

    public void BootstrapStructureMap() 
    { 
     ObjectFactory.Initialize(InitalizeStructureMapContainer); 
    } 

    #endregion 

    #region Private properties 

    private static bool HasStarted { get; set; } 

    #endregion 

    #region Private methods 

    private void InitalizeStructureMapContainer(IInitializationExpression x) 
    { 
     x.IgnoreStructureMapConfig = true; 
     x.AddRegistry<ViewModelRegistry>(); 
     x.AddRegistry<ApplicationServicesRegistry>(); 
     x.AddRegistry<RepositoriesRegistry>(); 
     x.AddRegistry<DataOperationsRegistry>(); 
    } 

    #endregion 

当我试图让实例注册表构造函数中的IApplicationRegisty我有一个错误(当然)。我没有完全理解如何正确使用StructureMap。可能是我应该做一些不同的方式。但无论如何,我可以获得一个在注册表构造函数中提前注册的某种类型的实例吗?

回答

7

今天我遇到了同样的问题。 Jeremy Miller(无关系)的答案是StructureMap没有设置为在配置时创建实例。

他推荐的解决方法是,我使用的是为设置创建容器。这是我的解决方案。

public class SettingsRegistry : Registry 
{ 
    public SettingsRegistry() 
    { 
     ForRequestedType<ISettingsProvider>().TheDefault.Is.OfConcreteType<AppSettingsProvider>(); 

     Scan(s => 
     { 
      s.TheCallingAssembly(); 
      s.With<SettingsScanner>(); 
     }); 
    } 
} 

public class RegistryNeedingSettings : Registry 
{ 
    public RegistryNeedingSettings() 
    { 
     var settingsContainer = new Container(new SettingsRegistry()); 
     var coreSettings = settingsContainer.GetInstance<CoreSettings>(); 

     //configuration needing access to the settings. 
    } 
} 

我感动的一切设置成自己的注册表,并确保这些设置注册表获取相关的注册表之前配置。

希望这会有所帮助。

相关问题