How exactly should I use BuildUp()?

Apr 9, 2008 at 8:56 AM
I have an ASP.NET Page class which I want to apply DI on. However, it seems not to be working. Could someone take a look and tell me what I am doing wrong?

I'm going to give a small example that clearly demonstrates what I do, instead of the ASP.NET code.

class Program
{
static void Main(string[] args)
{
IUnityContainer c = new UnityContainer();
c.RegisterType<Interface2, Class2>();
// If I add c.RegisterType<Interface1, Class1>() here, it works, but that does not seem right. Or is it? Why?

Interface1 instance = c.BuildUp<Interface1>(new Class1());
}
}

class Class1 : Interface1
{
InjectionMethod
public void DoInjection(Interface2 other)
{
// Never executed.
}
}

class Class2 : Interface2
{
}

interface Interface1
{
}

interface Interface2
{
}
Apr 9, 2008 at 10:15 AM
To clarify, I do not want to register it as a type - I want to register it as a pre-created singleton instance. However, even if I do RegisterInstance() before BuildUp(), the injection method is never executed. Only when I call RegisterType() before calling BuildUp().
Apr 9, 2008 at 4:49 PM
Try to do the following:

Interface1 instance = c.BuildUp(new Class1());

instead of:


Interface1 instance = c.BuildUp<Interface1>(new Class1());

Apr 9, 2008 at 6:59 PM
When you do BuildUp<Interface1>(new Class1()), you're telling the container to look at Interface1 to figure out what to inject.

Since the injection method is on the class, not the interface, it's not being found and not being run.

konst has the right approach.