Reputation: 2866
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.
Upvotes: 4
Views: 1116
Reputation: 1496
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);
Upvotes: 2