title: Injecting a specific instance of an interface using Autofac
body: <p>I am using ASP.NET MVC 3 and Autofac for my dependency injection.  I am using AutoMapper for my mapping.</p>
  
  <p>I have an IMapper class that I use for all my model view mappings.  So any any of my mapping classes can implement this interface.  In the controller below the constructor receives an IMapper instance, and in my User controller it might receive a different instance, maybe userMapper.  Getting back to the code below, I have a class called NewsMapper and it implements IMapper.  How do I setup dependency injection so that this controller must receive an instance of NewsMapper?  Please bear in mind that I might have another mapper called UserMapper.</p>
  
  <p>I have the following controller:</p>
  
  <pre><code>public class NewsController
  {
     private INewsService newsService;
     private IMapper newsMapper;
  
     public NewsController(INewsService newsService, IMapper newsMapper)
     {
        if (newsService == null)
        {
           throw new ArgumentNullException("newsService");
        }
  
        if (newsMapper == null)
        {
           throw new ArgumentNullException("newsMapper");
        }
  
        this.newsService = newsService;
        this.newsMapper = newsMapper;
     }
  }
  </code></pre>
  
  <p>I have the following configuration in my global.asax.cs:</p>
  
  <pre><code>var builder = new ContainerBuilder();
  builder.RegisterControllers(Assembly.GetExecutingAssembly());
  builder.RegisterType&lt;NewsService&gt;().As&lt;INewsService&gt;();
  builder.RegisterType&lt;NewsRepository&gt;().As&lt;INewsRepository&gt;();
  </code></pre>
  
  <p>UPDATED:</p>
  
  <p>My IMapper interface:</p>
  
  <pre><code>public interface IMapper
  {
     object Map(object source, Type sourceType, Type destinationType);
  }
  </code></pre>
  
  <p>My NewsMapper class:</p>
  
  <pre><code>public class NewsMapper : IMapper
  {
     static NewsMapper()
     {
        Mapper.CreateMap&lt;News, NewsViewModel&gt;();
        Mapper.CreateMap&lt;NewsViewModel, News&gt;();
     }
  
     public object Map(object source, Type sourceType, Type destinationType)
     {
        return Mapper.Map(source, sourceType, destinationType);
     }
  }
  </code></pre>
  
  <p>My controller action method where I do the mappings:</p>
  
  <pre><code>[HttpPost]
  public ActionResult Create(NewsViewModel newsViewModel)
  {
     // Check model state
     if (!ModelState.IsValid)
     {
        return View("Create", newsViewModel);
     }
  
     // Do mapping
     var news = (News)newsMapper.Map(newsViewModel, typeof(NewsViewModel), typeof(News));
  
     // Add to database via news service
  
     // Redirect to list view
     return RedirectToAction("List", "News");
  }
  </code></pre>