Home > Programming > MSBuild And MVC Area Projects using Autofac as IoC

MSBuild And MVC Area Projects using Autofac as IoC

I have a Web Project Folder structure MainMVCProject\Areas\MyArea in one of my projects. MyArea is a another MVC project. While setting up an MSBuild project, I realised that on building the main project using the task below, the contents of the child area MyArea where being copied to the parent MainMVCProject.

<MSBuild Projects=”$(WebFolder)\MainMVCProject.csproj”
Targets=”ResolveReferences;_CopyWebApplication”
Properties=”WebProjectOutputDir=$(DeployFolder)\www;
OutDir=$(DeployFolder)\www\bin\;Configuration=$(Configuration)” />

At first it was not obvious why, but managed to figure it out. The cause was because I had added a reference of MyArea project to MainMVCProject. The reason in the first place of adding that reference was to simplify the registration of controllers in the MyArea child Area project assembly using Autofac. Removing the reference fixed the MSBuild output but still needed to register the controllers with the Autofac Container.

In my solution I use a plugin architecture used in Umbraco, details here. In combination with a TypeFinder, I was already using a DependencyRegistrar for registering types to the Autofac Container. So I just added an implementation of IDependencyRegistrar in the MyArea child project which registers the controllers in that assembly. In Global.asax Application start method I find all types that do implement IDependencyRegistrar and execute the register method passing the container.

This overall fixed resolving controllers at run-time.

Categories: Programming Tags: ,
  1. John
    May 2, 2012 at 3:09 pm

    Useful article, thanks! Is there any chance you could post the code for the Application_Start event?

  2. Joseph Ssenyange
    May 5, 2012 at 4:45 am

    I use the method below:-

    public static void RegisterDepencies(ContainerBuilder containerBuilder, ITypeFinder typeFinder)
    {
    // Find all classes that implement IDependencyRegistrar see TypeFinder from umbraco
    var dependencyRegistrarTypes = typeFinder.FindClassesOfType();
    // Create instances. This is because we need to sort them in order they are to be registed in the container
    // For now the IDependencyRegistrar implementations are few, so this wont hurt much
    var dependencyRegistrarInstances = dependencyRegistrarTypes.Select(dependencyRegistrarType => (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrarType)).ToList();
    // Register types in their order
    dependencyRegistrarInstances = dependencyRegistrarInstances.OrderBy(t => t.Order).ToList();
    foreach (var dependencyRegistrar in dependencyRegistrarInstances)
    dependencyRegistrar.Register(containerBuilder);
    }

  1. No trackbacks yet.

Leave a reply to Joseph Ssenyange Cancel reply