views:

643

answers:

3

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

+1  A: 

As far as I know Unity tries (by default) to call the constructor with largest number of parameters and tries to resolve each of the parameters from the mappings. You shold add the mapping for IPreferenceStorageProvider or remove the constructor that requires this parameter.

If you don't want the IPreferenceStorageProvider parameter to by injected by unity maybe it shouldn't be declared as a constructor parameter at all. You can hard code instantiation of this object in default constructor.

PanJanek
THe problem is the "MyObject" is not my object.. It has about 15 constructors.. I can create it, but I have no control over its structure.. Why is Unity trying to new it up anyways? I created an instance and registered it.. It's now in the container as a singleton, It shouldn't be calling any constructors..???
gavin stevens
A: 

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?

Darrel Miller
A: 

Yeah, I think you nailed it. I wrote a wrapper class around my Unity container to return a singleton. I think in my actual implementation I was referencing the code in another assembly. Appears to be working now.

Gavin Stevens