I am using ServiceStack (5.12.0) in my ASP.NET service along with Unity Container. I am registering instances of same type as follows
public static IUnityContainer Create()
{
container.RegisterType<ITest, Clock1>(new ContainerControlledLifetimeManager());
container.RegisterType<ITest, TestClock>("TestClock", new ContainerControlledLifetimeManager());
}
Resolve in UnityContainerAdapter with following methods
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);
}
This is how I am injecting instance in servicestack handler
public class testRequestHandlers: Service
{
private readonly ITest _clock;
public testRequestHandlers( ITest clock)
{
this._clock = clock;
}
}
I want to use "TestClock" in other handler, but each time it gives instance of Clock1 and I could not able to figure out how to do it.I have tried following
public class test2RequestHandlers : Service
{
private readonly ITest _clock;
public test2RequestHandlers([Dependency("TestClock")] ITest clock)
{
this._clock = clock;
}
}
Please help.
CodePudding user response:
Third Party IOC's provide the dependencies to inject but they don't handle construction of Service classes so Unity's attributes have no effect.
As you can only have a single registration for a given type (e.g. ITest
) you would typically register dependencies against different types to specify which dependency to use, e.g:
container.RegisterType<TestClock>(new ContainerControlledLifetimeManager());
public class Test2RequestHandlers : Service
{
private readonly ITest clock;
public Test2RequestHandlers(TestClock clock)
{
this.clock = clock;
}
}
Alternatively you can resolve named dependencies from ServiceStack's IOC within your Service implementation with:
this.clock = HostContext.Container.ResolveNamed<ITest>("TestClock");