I've written a class that has some dependencies it resolves from the unity container.
From my main class I create a new object
MyObject myObject = new MyObject();
I register it with my Unity Container
UContainer.RegisterInstance<MyObject>(myObject, new ExternallyControlledLifetimeManager());
the I create the type that needs this as a dependency
ConsumerObject consumer = new ConsumerObject();
the consumer looks like this:
public class ConsumerObject
{
public ConsumberObject()
{
theObject = (MyObject)UContainer.Resolve(typeof(MyObject));
}
}
this throws an exception:
Resolution of the dependency failed, type = "MyObject", name = "". Exception message is: The current build operation (build key Build Key[MyObject, null]) failed: The parameter pp could not be resolved when attempting to call constructor MyObject(IPreferenceStorageProvider pp). (Strategy type BuildPlanStrategy, index 3)
Why is my resolve call trying to call another contsructor on the type? I already created it and registered the instance.. I also tried it like: theObject = UContainer.Resolve<MyObject>();
doesn't seem to make any difference..
Thanks
I think the problem is that you using ExternallyControlledLifetimeManager. In this case Unity container holds only weak reference to your instance. And when you try to resolve, your instance already garbage collected. That's why the default LifeTimeManager for .RegisterInstance() is ContainerControlledLifeTimeManager. And Darrel Miller's case it works, because it not GC-ed yet. Try register your instance this way:
UContainer.RegisterInstance<MyObject>(myObject);
I'm not sure why you are seeing the behaviour you are. I just created a test that duplicated your scenario and it worked fine.
Have you tried something like this,
public class ConsumerObject
{
public ConsumberObject(MyObject myObject)
{
theObject = myObject
}
}
and then using UContainer.Resolve<MyObject>()
?
The only thing that I can think of is when you access UContainer.RegisterInstance and then UContainer.Resolve you are actually accessing two different containers. Could you show us how you are declaring UContainer?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With