Wednesday, April 28, 2010

Customizing controller factory used Structure Map

I recently started to working on new version of ASP.NET MVC 2. And the first thing I must to do is customizing the controller factory to using IoC for getting controller type. In the first stable version of ASP.NET MVC (1.0), I had done it, but in this version it had some thing changed. In special, when you inherited from the DefaultControllerFactory class it didn't have the RequestContext instance to the constructor. In the version 2, the constructor is have 2 parameters.

But why do you need customizing the Controller Factory? That because you need injecting some instances to the constructor of Controller. For example, you coded the CategoryFacade class and wanted to injecting into the CategoryController for getting some data from Database. this is a situation that you need customizing the Controller Factory.

Now, we started to implementing it. The first thing you need is inheriting the DefaultControllerFactory class:
In my case, I used Structure Map  for IoC container. And in my Registry class, I need scanning the Web assembly as below:

Now, we must notify for ASP.NET engine for it can understand my custom Controller. How do I make it?. It's really easy, I implemented as below:
Don't confuse about it. At here, I only implement the Bootstrapper for my application. So don't care about it. We only concentrate on the ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()). As you see I replaced the default Controller Factory with my custom Controller Factory.

Next step, we need registering all my configuration, so when the website started we shall have all instances to using. In this post, I implemented the Bootstrapper for booting the Website. So we only write the simple line of code as below in Global.asax:

As you see, we registered all Areas and continued to booting my website by the Bootstrapper. Just simple thing! Now saving all codes, and press F5 in Visual Studio's IDE. We shall possible injecting the Category Facade instance as here:

Finally, in order to writing this post, I referenced many articles from Internet. And this is my resources:

No comments:

Post a Comment