Vlad's blog

In programming veritas

Posts Tagged ‘DI

Task Manager: dependency injection

leave a comment »

This is the fourth post of a series of posts on developing Web applications using ASP.Net MVC. The previous two posts are available here:

The source code is available on CodePlex.

In any application, there is the problem of managing dependencies between components. There is no single solution here. In many cases, there is nothing wrong when a client explicitly creates instances of the required services. In our case we need to look at the dependencies between the application layers. The following diagram shows that the Presentation layer depends on the Domain layer and Data Access layer, and Domain layer depends on the Data Access layer.

Indeed, ProjectController, TaskController and AccountController require a reference to the repository to perform CRUD operations. Some operations require a reference to IProjectDeleteService or IUserDeleteService or IUserActionLogger. Implementations of services also require a reference to the repository. Technically, all three layers are represented by three different assemblies. All interfaces are declared as public, while the implementation declared as internal.
One possible solution here is to use a DI container. There are a sufficient number of libraries that provide functionality of DI container, so the best choice is often determined by personal preference. Personally I like Autofac. The idea of ​​modules is useful for isolation of layers. Thus, each layer will be represented by own module, which registers the dependencies. For example, DomainLayer registers services that are provided by Domain layer.

public class DomainLayer : Module
    protected override void Load(ContainerBuilder builder)

Instances of modules are created to initialize DI container at the application startup.

protected void Application_Start()
    var builder = new ContainerBuilder();

    builder.RegisterModule(new DataAccessLayer());
    builder.RegisterModule(new DomainLayer());
    builder.RegisterModule(new PresentationLayer());

    IContainer container = builder.Build();

    // Setup DI as default MVC controller factory
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Another task that can be solved by DI container is to manage the lifetime of objects. For example, in order to create instance of ProjectController you need the following services.

  • ProjectRepository
  • UserActionLogger
  • TaskManagerDbContext
  • ProjectDeleteService

ProjectRepository also depends on TaskManagerDbContext. We need to make sure we have only one instance of TaskManagerDbContext in current HTTP request. Otherwise every service will get own copy of TaskManagerDbContext.

When a request is made for a service, Autofac can return a single instance within some kind of context, e.g. a thread or an HTTP request. To do this, call InstancePerLifetimeScope() method when registering the dependency.

public class DataAccessLayer : Module
    protected override void Load(ContainerBuilder builder)
        Database.SetInitializer(new DatabaseInitializer()); // Initialize database


Autofac is smart enough to undestand Lazy class which is usually used for lazy initialization. For example, IProjectDeleteService needed to create ProjectController, but in reality it is only required when processing a request to delete a project. In this case it is convenient to use lazy initialization.

public ProjectController(IProjectRepository projectRepository, 
Lazy<IProjectDeleteService> projectDeleteService, 
IUnitOfWork unitOfWork, 
IUserActionLogger userActionLogger, TabContainer tabContainer)
    Contract.Requires(projectRepository != null);
    Contract.Requires(unitOfWork != null);

    _projectRepository = projectRepository;
    _tabContainer = tabContainer;
    _projectDeleteService = projectDeleteService;
    _unitOfWork = unitOfWork;
    _userActionLogger = userActionLogger;

    if(log.IsDebugEnabled) log.Debug("Created ProjectController");

Generally, Autofac supports a well defined system of relationship types. More information about the features can be found in blog of one of the developers.


Written by vsukhachev

January 8, 2012 at 1:34 pm

Posted in Development

Tagged with ,