Twitter LinkedIn Github

JetBrains

IoC containers are great. They take away the burden of having to create dependencies before using things, and when your dependencies start to become complex and you have a whole graph of them, it can get ugly if you're not using one. So to the rescue comes Mr. Unity, Mr. StructureMap, Don AutoFac or the Hero Ninject. Take your pick.

But all this greatness can come back and bite you on the tip of your pinky finger (the one on the right hand). Why is that?

Let's assume you have the following class:

   1: public class CustomerServices    
   2: {   
   3:    private readonly ICustomerRepository _customerRepository;    
   4:  
   5:    public CustomerServices(ICustomerRepository repository) 
   6:    {
   7:  
   8:      _customerRepository = repository;   
   9:  
  10:    }  
  11:  
  12: ...

 

and you decide to introduce a new dependency

   1: public class CustomerServices    
   2: {   
   3:    private readonly ICustomerRepository _customerRepository;    
   4:    private readonly IAuditingServices _auditingServices;
   5:  
   6:    public CustomerServices(ICustomerRepository repository, IAuditingServices auditingServices) 
   7:    {
   8:  
   9:      _customerRepository = repository;   
  10:      _auditingServices = auditingServices;
  11:  
  12:    }  
  13:  
  14: ...

 

That code will compile, as will any other code throughout the project that is using CustomerServices. It's only then when the container tries to resolve CustomerServices, will it see that you have not registered any type for IAuditingServices. And this happens at runtime.

So it's important to create configuration tests for your containers.