如何在StructureMap Registy构造函数中获取某种类型的实例(在不同的注册表中注册)?我想使用这样的代码:
public RepositoriesRegistry() { IApplicationSettings lApplicationSettings = ObjectFactory.GetInstance(); 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 ().TheDefault.IsThis( lSupportedDevicesEntities); ForRequestedType ().TheDefault.IsThis( new SupportedDevicesRepository(lSupportedDevicesEntities)); }
IApplicationSettings是应用程序设置的接口.实现此接口的具体类型(当前为ConfigFileApplicationSettings类)在另一个注册表中注册,如下所示:
public ApplicationServicesRegistry() { ForRequestedType().TheDefault.IsThis( new ConfigFileApplicationSettings()); }
这两个注册表都在Bootstrapper中注册:
#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(); x.AddRegistry (); x.AddRegistry (); x.AddRegistry (); } #endregion
当我尝试在注册表构造函数中获取IApplicationRegisty的实例时,我遇到了错误(当然).我没有完全理解如何以正确的方式使用StructureMap.也许我应该以不同的方式做事.但无论如何我可以在Registry构造函数中获得早期注册的某种类型的实例吗?
我今天遇到了同样的问题.Jeremy Miller(没有关系:))的答案是StructureMap没有设置为在配置时创建实例.
他推荐的解决方法和我使用的是为设置创建一个容器.这是我的解决方案.
public class SettingsRegistry : Registry { public SettingsRegistry() { ForRequestedType().TheDefault.Is.OfConcreteType (); Scan(s => { s.TheCallingAssembly(); s.With (); }); } } public class RegistryNeedingSettings : Registry { public RegistryNeedingSettings() { var settingsContainer = new Container(new SettingsRegistry()); var coreSettings = settingsContainer.GetInstance (); //configuration needing access to the settings. } }
我将所有设置移动到自己的注册表中,并确保在依赖注册表之前配置设置注册表.
希望这可以帮助.