This article describes how to inject an object into controllers in ASP.NET MVC. To do that we shall use either DefaultControllerFactory class or IControllerFactory interface that help us in creating custom controller factory.

Introduction

While developing real time application in ASP.NET MVC, we might come to a point where we feel the need of injecting an object into ASP.NET MVC controller instance so that we can call methods of that objects in our controller classes. By default ASP.NET MVC creates a controller using parameter less constructor and we will not be able to inject our class into it. Controller dependency injection is one way that let us do that.

To inject our class into ASP.NET MVC controller, we can follow two approaches

Overriding DefaultControllerFactory class that comes along with ASP.NET MVC Framework

Implementing IControllerFactory interface methods of ASP.NET MVC

Purpose: Controller dependency injection in ASP.NET MVC

The purpose of dependency injection in MVC controller is to achieve following where we are passing the parent class to the constructor of the Controller so that we can use its methods into action methods. In this case, we are using GetName() and GetLoginDetails() method of the Parent class inDefaultControllerFactoryMethod method.

In this approach, we create our own controller factory class by inheriting DefaultControllerFactory class that is part of ASP.NET MVC framework and override its GetControllerInstance method.

Look at below code snippet carefully, In GetControllerInstance method, we are instantiating the Parent class that is being passed to the Activator.CreateInstance method only when the controller name is "Home" otherwise the default constructor of the controller is instantiated without any parameter.

Now, if we call the DefaultControllerFactoryMethod of the Home controller we will get the respective output. The other controller doesn't get affected by this as we have passed the instance of the Parent class only when controllerName is "Home" in the DefaultControllerFactoryMethod class declared above.

Word of caution

As we can see that the purpose of injecting an object in the controllers is being served using above two approaches however in the large real time application this again might be a lot of work. So the ideal solution to implement dependency injection in ASP.NET MVC controller is to use IOC containers like Windsor Castle, Unity, Ninject etc. that we may discussion in coming articles.

Hope this article was useful, if this helps do share this to the social websites and refer dotnetfunda.com to your friends and colleagues. Do write your comments below.