Is there any configuration to tell Unity to share same instance for each resolve?
class A:IA {
A(Iref @ref,IB x) {
@ref.Exec(() => x.Foo());
}
...
}
class B:IB {
IC c;
B(IC c) {
c=c
}
void Foo() { c.Bar(); }
}
class C:IC {
C(Iref @ref) // I need Unity to give me the same instance that is resolved in Class A
{
@ref....
}
void Bar() {}
...
}
I have tried to register Iref
by PerResolveLifetimeManager
but the problem I have is it shares the same instance for all dependencies not for each one.
The problem looks like this
Class FooController:Controller
{
FooController(IA test1 , IA test2)
{
// Unity resolves Iref one time so it is shared between test1 and also test2!
// but what i need is Iref instance for each IA, basically a singleton
// scoped just inside IA in order to be shared between Class A and C
}
FooController()
{
//so the only solution that resolve it properly is by forcing the resolve manually,
// the Unity container instantiates Iref for each instance (test1 and test2)
// and of course it's shared between class A and also C for each instance of IA
IA test1 = container.Resolve<IA>();
IA test2 = container.Resolve<IA>();
}
}
My question is there any solution to fix this using Dependency Injection?
You simply register the IA type with the TransientLifetimeManager
and all other dependent types, with their own lifetime. That means that IA can have singleton dependencies and they will be resolved as singletons (ContainerControlledLifetimeManager
), while IA will be resolved on every injection.
TransientLifetimeManager. For this lifetime manager Unity creates and returns a new instance of the requested type for each call to the Resolve or ResolveAll method. This lifetime manager is used by default for all types registered using the RegisterType, method unless you specify a different lifetime manager.
ContainerControlledLifetimeManager which registers an existing object as a singleton instance. For this lifetime manager Unity returns the same instance of the registered type or object each time you call the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. This lifetime manager effectively implements a singleton behavior for objects. Unity uses this lifetime manager by default for the RegisterInstance method if you do not specify a different lifetime manager. If you want singleton behavior for an object that Unity will create when you specify a type mapping in configuration or when you use the RegisterType method, you must explicitly specify this lifetime manager. If you registered a type mapping using configuration or using the RegisterType method, Unity creates a new instance of the registered type during the first call to the Resolve or ResolveAll method or when the dependency mechanism injects instances into other classes. Subsequent requests return the same instance.
Read more here.