4

I'm trying to instantiate a new class using the type passed in and then use the Unity Container to build up the object to inject its dependencies.

The Unity Container does not have any extensions/strategies. I'm just using an unaltered unity container. It's properly loading the configuration and used in other places in the code to resolve dependencies on items.

I've got the following code:

// Create a new instance of the summary.
var newSummary = Activator.CreateInstance(message.SummaryType) as ISummary;
this.UnityContainer.BuildUp(newSummary.GetType(), newSummary);
// Code goes on to use the variable as an ISummary... 

The [Dependency] properties (which are public and standard get; set;) of the class are not being injected. They are all still null after the BuildUp method is called. Is there something obvious that I'm doing wrong?

Thanks in advance.

3
  • Do you have any extensions/strategies added to the container? Commented Jun 4, 2013 at 14:30
  • None. I'm using the unity container as is. Commented Jun 4, 2013 at 14:33
  • Having the same problem here Commented Jun 12, 2013 at 13:00

1 Answer 1

2

When you call newSummary.GetType(), it will return the underlying type. In this case, whatever SummaryType happens to be (say MySummaryType). When it calls BuildUp, there's a mismatch in the type, so it won't work.

// Code translates to:
this.UnityContainer.BuildUp(typeof(MySummaryType), newSummary);
// But newSummary is ISummary

To get BuildUp to work:

this.UnityContainer.BuildUp<ISummary>(newSummary);

or

this.UnityContainer.BuildUp(typeof(ISummary), newSummary));

Another option you can use (IHMO the preferred way) is to use Unity's Resolve method. BuildUp is used for an object that you don't have control over its creation. This isn't the case looking at your code.

ISummary newSummary = this.UnityContainer.Resolve(message.SummaryType);
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, would you have some other ideas if this solution is not the case?
What actually helped me was instead of specifying the parental type of the object, I had to specify particular instance type, something like: (T)moduleDescriptor.ModuleContext.BuildUp(instance.GetType(), instance);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.