Please follow the following steps to implement the dependency injection in the MVC.
Step1:- Install "Unity.MVC4" Nuget Package.
Step2:- Map interfaces with classes as followimg
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IUser, UserComponent>();
container.RegisterType<IService, ServiceComponent>();
RegisterTypes(container);
return container;
}
Step3:- In global.ajax file set Bootstrapper.Initialise() function.
protected void Application_Start()
{
Bootstrapper.Initialise();
}
Step5:- Start inject constructor of controller as following:-
public class HomeController : Controller
{
IUser UserComponent = null;
IService ServiceComponent = null;
public HomeController(IUser userComponent, IService serviceComponent)
{
if (userComponent == null)
{
throw new ArgumentNullException();
}
this.UserComponent = userComponent;
if (serviceComponent == null)
{
throw new ArgumentNullException();
}
this.ServiceComponent = serviceComponent;
}}
No comments:
Post a Comment