Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity register instance and resolve

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

like image 555
gavin stevens Avatar asked Feb 05 '10 07:02

gavin stevens


2 Answers

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);
like image 120
Yury Pekishev Avatar answered Oct 26 '22 11:10

Yury Pekishev


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?

like image 24
Darrel Miller Avatar answered Oct 26 '22 11:10

Darrel Miller