C# Dependency Injection Placement – Best Practices

cdependency-injection

This is my first time using Unity so bear with me for a moment. I have a sample Visual Studio 2012 project with 4 projects (but only two of these projects will be used with Unity). This is the following setup of the projects:

  1. Database – WinForm project that displays a Master Detail Form
  2. DatabaseUtilities – A class library that implements the Repository pattern. The interface is called ISampleRepository.cs and the type is called SampleRepository.cs

Project Setup http://www.omnicom-innovations.com/Snippets/Images/Unity/UnityQuestion2.png

I've been reading on Dependency Injection and I understand that the UnityContainer code gets placed in the starting location of where the application is going to run.

Should it go in Database.Program.cs or in a Bootstrapper.cs class that resides in the DatabaseUtilities project?

I ask because Program.cs is technically the entry point to the Database WinForm project.

Here's my code for Bootstrapper.cs:

using Microsoft.Practices.Unity.Configuration;

namespace DatabaseUtilities
{
    public class Bootstrapper
    {
        private static UnityContainer _container;

        public static ISampleRepository<Employee> LoadSampleRepository()
        {
            _container = new UnityContainer();
            _container.RegisterType(typeof(ISampleRepository<Employee>), typeof(SampleRepository));
            var obj = _container.Resolve<ISampleRepository<Employee>>();


            return obj;            
        }
    }
}

I'm thinking of referencing the Bootstrapper.cs from Program.cs in the Database project.

But would this be considered a best practice? Furthermore, I want to make sure that I don't shoot myself in the foot later on. Let's say I decide to implement another form from the MasterDetail form and I need to perform a different CRUD operation (i.e. an update operation). I want to be able to use my class that implements IRepository.

Am I looking at this from the right angle?

Best Answer

Basically it would not be a good idea to put container logic inside a library. When you want to use the DatabaseUtilities library in another project that uses another dependency injection framework, you still have the dependency with Unity.
So in this case it would be better to move the bootstrap class to your main project.
Putting the bootstrap logic inside the Program.cs or inside a separate class is basically a matter of opinion, but thinking about the Single Responsibility Principle I would say keep them separate.

Alternatively you could create another project that is purely responsible for the configuration part of the container, but that is probably overkill in this situation.

Yet another alternative is to merge both projects into one, because do you really need to have a project separation, can't you just put the DatabaseUtilities in a separate namespace inside your main project?