Skip to main content

ASP.NET MVC 4 - ControllerFactory And StructureMap



StructureMap is an IoC container that we can use to inject implementations into the client. To do this in ASP.NET MVC we will use the constructor of the controller. Create a new ASP.NET MVC 4 project and install StructureMap via NuGet. When the package is installed a reference to StructureMap is automatically created.

Create a class named BootStrapper inside the root of the MVC project with the following code listing:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using StructureMap;
using StructureMap.Configuration.DSL;
using Mvc4ControllerFactoryAndStructureMap.Services;
namespace Mvc4ControllerFactoryAndStructureMap
{
    public class BootStrapper
    {
        public static void ConfigureDependencies()
        {
            ObjectFactory.Initialize(x => x.AddRegistry<ControllerRegistry>());
        }
    }
    public class ControllerRegistry : Registry
    {
        public ControllerRegistry()
        {
            For<IProductService>().Use<ProductService>();
        }
    }
}
Inside the ControllerRegistry class you specify the implementation(s) that belongs to a specific interface. The ConfigureDependencies method initializes the registry with the StructureMap framework.
Create another class named StructureMapControllerFactory inside the root of the MVC project with the following code listing:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Web.Mvc;
using System.Web.Routing;
using StructureMap;
namespace Mvc4ControllerFactoryAndStructureMap
{
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return ObjectFactory.GetInstance(controllerType) as IController;
        }
    }
}
The StructureMapControllerFactory let StructureMap inject implementations inside the constructor of our controllers. Let's see how that looks like.
IProductService (Interface)
?
1
2
3
4
5
6
7
8
9
using Mvc4ControllerFactoryAndStructureMap.Models;
namespace Mvc4ControllerFactoryAndStructureMap.Services
{
    public interface IProductService
    {
        Product GetProduct();
    }
}
ProductService (Implements IProductService)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Mvc4ControllerFactoryAndStructureMap.Models;
namespace Mvc4ControllerFactoryAndStructureMap.Services
{
    public class ProductService : IProductService
    {
        public Product GetProduct()
        {
            Product product = new Product();
            product.Name = "Test";
            product.Description = "This product is awesome.";
            return product;
        }
    }
}
ProductController (Implementations injected via constructor)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Web.Mvc;
using Mvc4ControllerFactoryAndStructureMap.Services;
using Mvc4ControllerFactoryAndStructureMap.Models;
namespace Mvc4ControllerFactoryAndStructureMap.Controllers
{
    public class ProductController : Controller
    {
        private readonly IProductService _productService;
        public ProductController(IProductService productService)
        {
            _productService = productService;
        }
        public ActionResult Index()
        {
            Product product = _productService.GetProduct();
            return View(product);
        }
    }
}
As you can see the constructor of the ProductController takes an IProductService parameter and stores that in _productService. StructureMap has the ability to look at what the constructor expects and inject the implementation. To provide this implementation to the controllers constructor you created a custom controller factory: StructureMapControllerFactory. Every method inside the controller can now use the ProductService implementation by using _productService.
Now let's configure the dependencies at startup because we only need to do that once. Open global.asax and add the following lines to Application_Start:
?
1
2
BootStrapper.ConfigureDependencies();
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
The BootStrapper.ConfigureDependencies method registers all the dependencies with StructureMap. After that we change the current controller factory to our own StructureMapControllerFactory so that the dependencies are injected when needed.
That's it. You can download the source code and hit Ctrl-F5 to see it working: Download

Comments

Popular posts from this blog

How To Install Age Of Empires 2: Forgotten Empires

There is a new unofficial expansion pack for Age of Empires 2 called Forgotten Empires. To install Forgotten Empires you need the original Age of Empires II "Age of Kings" and the official expansion pack "The Conquerors". When Age of Empires 2 came out I could play this game non stop for hours and with this new expansion pack it looks like that's still possible even though I'm not really much of a gamer ;). Features 5  brand new civilizations 30  new technologies 9  new units 1000  population limit 11  new maps 1  new building 2  new architecture sets 20  new scenario editor objects ?  new campaigns Full  unlimited  resolutions (Widescreen included) Install Make sure to have Age of Empires II: The Conquerors installed Download the installer exe | zip Unzip the file into your Age of Empires II Installation folder (typically C:\Program Files\Microsoft Games\Age of Empires II\) Select your language Click Install

Block Spotify Ads

Spotify is a digital music service that gives you access to millions of songs without having to pay a penny.  Off couse you can pay so you don't have to listen to those ads anymore, but there is a free way to block Spotify ads. The best ad blocker at the moment is Blockify that mutes Spotify whenever it detects an audio ad. When the ad finished playing it will unmute Spotify and play your tracks. Blockify also adds customizable hotkeys to Spotify, so you can skip tracks, play, pause, shuffle, and change the volume with keyboard shortcuts. Features: Mutes Spotify whenever it detects an audio ad. Play your own MP3s during adverts. Control Spotify via keyboard hotkeys. Easy to use, totally portable. Unlike every other advert blocker, it doesn't rely on a list! Download Blockify

Minecraft - Feed the Beast launcher - Part 1

Have you tried to implement a mod in Minecraft? All the research on how to do it, if mod version x.xx is compatible for your current Minecraft version and a lot more. Thanks to the FTB launcher, which is short for Feed the Beast Launcher, that is ancient history. FTB launcher is an program designed to play modpacks without any configuring. With just a couple of clicks you can start an available modpack and the launcher will download en configure everything for you. It has the ability to download maps, texturepacks, different mod packs and more. The official site can be found here: http://www.feed-the-beast.com Because there is a lot to talk about this article will be split into two parts. The first will cover the following topics of the launcher: News; Options; Maps; Texturepacks. The second part will contain the most important feature of the launcher, which is the Modpack section. The modpack section will be divided into the following topics: Modpacks Filt