0
我不知道如何我將使用Unity以下....團結,每個請求的生命週期
我有其中「按要求」創建的對象,在大多數情況下,一個簡單的代碼位I使用注射工廠建ILogger實例(每個請求)...如下...
container.RegisterType<ILogger>(new InjectionFactory(factory => factory.Resolve<ILoggingFactory>()));
到目前爲止很簡單...但我想象在單個Web請求多次調用多個對象,當請求到達時,我想創建並使用上面的日誌記錄器,但我希望後續調用用於已存在的實例....如下
// This should use the RegisterType functionality (above) to create a new instance of the logger
public class A : IAIntf
{
public AConstructor(ILogger log)
{ .. }
}
// This should use the logger which was constructed when A was created
public class B : IBIntf
{
public BConstructor(ILogger log)
{ .. }
}
此代碼正確地創建用於類A的接口,但無法創建B類的情況下,使用重用接口..
unity.GetService(typeof(T)); // Unity thinks T is IBIntf (which is correct)
..但分辨率期間統一未能重用ILogger類創建當A類被實例化時。
我認爲問題在於,統一需要保持對ILogger接口一輩子,所以我調整了容器的註冊如下,而是一個新的ILogger創建:(
container.RegisterType<ILogger>(new HttpRequestLifetimeManager<ILogger>(),
new InjectionFactory(factory => factory.Resolve<ILoggingFactory>()));
// Also tried
container.RegisterType<ILogger>(new PerResolveLifetimeManager(),
new InjectionFactory(factory => factory.Resolve<ILoggingFactory>()));
我怎麼知道團結給我一個B類的新實例,但重用了也傳遞給A類的ILogger接口,而不是創建一個新的ILogger實例?