[英]Castle Windsor “Late bound” components
我的容器中已注冊了多個組件,Windsor可以毫無問題地注入它們。 現在,我以這種方式為NHibernate ISessionFactory添加了新的注冊:
foreach (KeyValuePair<string, string> _tenantItem in _contextWrapper.TenantsConnectionStrings)
{
var config = Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008
.UseOuterJoin()
.ConnectionString(_tenantItem.Value)
.FormatSql()
.ShowSql()
)
.ExposeConfiguration(ConfigurePersistence)
.ProxyFactoryFactory(typeof(ProxyFactoryFactory))
.BuildConfiguration();
Kernel.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(config.BuildSessionFactory)
.Named(_tenantItem.Key)
.LifestyleTransient()
);
}
現在,如果我嘗試檢查我的容器,我會看到:
組件實現是“后期綁定”的,Windsor不會注入它。
怎么了? 我可以檢查什么?
這里有兩個獨立且無關的問題,因此讓我依次回答。
組件描述中所說的“后期綁定”僅表示Windsor不靜態地知道ISessionFactory
的實現類型。 這不是擔心的原因。
這完全取決於您指定的工廠方法config.BuildSessionFactory()
在您的情況下為config.BuildSessionFactory()
來構建實例,並且每次都可能不是同一類型。
一個人可以實現如下的工廠方法:
public ISessionFactory BuildSessionFactory()
{
if (Today == DayOfWeek.Friday)
{
return new BeerOClockSessionFactory();
}
return SomeOtherSessionFactory();
}
這是正常的。
您提示的另一個問題表明您可能遇到了意外的行為,即對ISessionFactory
的依賴關系未按預期滿足。
可悲的是,除非您對此有更多的解釋,否則請分享您看到的那種錯誤,我認為除了說“它應該可以工作”之外,我沒有什么可以幫助的。
同樣,在我們討論這個問題時,我完全同意@raulg的觀點,即使會話工廠成為瞬態並不是一個特別好的主意。
可能不喜歡您在運行時創建配置實例。
您最好為配置創建一個合適的類,將其注冊到容器中,然后使用該類來創建ISessionFactory實例。
public class MySessionFactoryBuilder : IMySessionFactoryBuilder
{
private FluentConfiguration _fluentConfiguration = null;
public MySessionFactoryBuilder()
{
}
void Initialize(string connectionStringKey)
{
IPersistenceConfigurer persistenceConfigurer = null;
persistenceConfigurer = MsSqlConfiguration.MsSql2008
.UseOuterJoin()
.ConnectionString(connectionStringKey)
.FormatSql()
.ShowSql()
;
_fluentConfiguration = Fluently.Configure()
.Database(persistenceConfigurer)
.ExposeConfiguration(ConfigurePersistence)
.ProxyFactoryFactory(typeof(ProxyFactoryFactory))
.BuildConfiguration()
;
}
public ISessionFactory BuildSessionFactory(string connectionStringKey)
{
Initialize(connectionStringKey);
return _fluentConfiguration.BuildSessionFactory();
}
}
您可以正常注冊。 然后,在安裝程序循環中注冊多個ISessionFactory,每個租戶一個:
foreach (KeyValuePair<string, string> _tenantItem in _contextWrapper.TenantsConnectionStrings)
{
container.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(k => k.Resolve<MySessionFactoryBuilder>().BuildSessionFactory(_tenantItem.Value))
.Named(_tenantItem.Key),
Component.For<ISession>()
.UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
.Named(_tenantItem.Key + "-nhsession")
.LifeStyle.Transient
);
}
注意,我注冊了ISession瞬態,但沒有注冊ISessionFactory。 通常,您希望將ISessionFactory保留得盡可能長,因為創建起來很昂貴。
我還沒有測試它,但是我猜它會解決它,因為在編譯時就知道會話工廠構建器的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.