我在我的 ASP.NET 服務中使用 ServiceStack (5.12.0) 以及 Unity Container。我正在注冊相同型別的實體,如下所示
public static IUnityContainer Create()
{
container.RegisterType<ITest, Clock1>(new ContainerControlledLifetimeManager());
container.RegisterType<ITest, TestClock>("TestClock", new ContainerControlledLifetimeManager());
}
使用以下方法在 UnityContainerAdapter 中決議
public T TryResolve<T>()
{
if (_container.IsRegistered<T>())
return _container.Resolve<T>();
return default(T);
}
public T Resolve<T>()
{
return _container.Resolve<T>();
}
public T Resolve<T>(string name)
{
return _container.Resolve<T>(name);
}
這就是我在 servicestack 處理程式中注入實體的方式
public class testRequestHandlers: Service
{
private readonly ITest _clock;
public testRequestHandlers( ITest clock)
{
this._clock = clock;
}
}
我想在其他處理程式中使用“TestClock”,但每次它都會給出 Clock1 的實體,我無法弄清楚如何去做。我試過以下
public class test2RequestHandlers : Service
{
private readonly ITest _clock;
public test2RequestHandlers([Dependency("TestClock")] ITest clock)
{
this._clock = clock;
}
}
請幫忙。
uj5u.com熱心網友回復:
第三方 IOC 提供要注入的依賴項,但它們不處理 Service 類的構造,因此 Unity 的屬性無效。
由于您只能對給定型別(例如ITest
)進行一次注冊,因此您通常會針對不同型別注冊依賴項以指定要使用的依賴項,例如:
container.RegisterType<TestClock>(new ContainerControlledLifetimeManager());
public class Test2RequestHandlers : Service
{
private readonly ITest clock;
public Test2RequestHandlers(TestClock clock)
{
this.clock = clock;
}
}
或者,您可以在 Service 實作中從 ServiceStack 的 IOC 決議命名依賴項:
this.clock = HostContext.Container.ResolveNamed<ITest>("TestClock");
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/513933.html
上一篇:如何在R中逐行閱讀PDF?
下一篇:Node.js服務的監控機制