Search code examples
c#dependency-injectionunity-containerconstructor-injection

Constructor Injection in C#/Unity?


I'm using C# with Microsoft's Unity framework. I'm not quite sure how to solve this problem. It probably has something to do with my lack of understanding DI with Unity.

My problem can be summed up using the following example code:

class Train(Person p) { ... }

class Bus(Person p) { ... }

class Person(string name) { ... }

Person dad = new Person("joe");
Person son = new Person("timmy");

When I call the resolve method on Bus how can I be sure that the Person 'son' with the name 'timmy' is injected and when resolving Train how can I be sure that Person 'dad' with then name 'joe' is resolved?

I'm thinking maybe use named instances? But I'm at a loss. Any help would be appreciated.

As an aside, I would rather not create an IPerson interface.


Solution

  • One way to solve this would be to use an injection constructor with a named registration.

    // Register timmy this way  
    Person son = new Person("Timmy");  
    container.RegisterInstance<Person>("son", son);  
    
    // OR register timmy this way  
    container.RegisterType<Person>("son", new InjectionConstructor("Timmy"));  
    
    // Either way, register bus this way.  
    container.RegisterType<Bus>(new InjectionConstructor(container.Resolve<Person>("son")));  
    
    // Repeat for Joe / Train