Search code examples
c#dependency-injectionunity-container

How to correctly inject service in constructor ?


I have a simple interface and a simple console application.

public interface ICustomerService
{
    string Operation();
}

and one service which implements the above interface.

public class CustomerService : ICustomerService
{
    public string Operation()
    {
        return "operation";
    }
}

Now I declare an unity container in order to use dependency injection pattern and a class called CustomerController.

var container = new UnityContainer();
container.RegisterType<ICustomerService, CustomerService>();
CustomerController c = new CustomerController();
c.Operation();

I want to inject the service inside CustomerController.

public class CustomerController
{
    private readonly ICustomerService _customerService;

    public CustomerController()
    {

    }
    [InjectionConstructor]
    public CustomerController(ICustomerService customerService)
    {
        _customerService = customerService;
    }

    public void Operation()
    {
        Console.WriteLine(_customerService.Operation());
    }
}

I know that for Web API and MVC application it's used a DependencyResolver.

DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 

But how to inject service correctly in a simple console app ?


Solution

  • Register the CustomerController with the container as well.

    public static void Main(string[] args) {
    
        var container = new UnityContainer()
            .RegisterType<ICustomerService, CustomerService>()
            .RegisterType<CustomerController>();
    
        CustomerController c = container.Resolve<CustomerController>();
        c.Operation();
    
        //...
    }
    

    The container will inject the dependency when resolving the controller

    There is actually no longer a need for the default constructor and [InjectionConstructor] attribute if the dependency is only going to be used via the other constructor

    public class CustomerController {
        private readonly ICustomerService _customerService;
    
        [InjectionConstructor]
        public CustomerController(ICustomerService customerService) {
            _customerService = customerService;
        }
    
        public void Operation() {
            Console.WriteLine(_customerService.Operation());
        }
    }