I am new to ASP.NET MVC 4. I have used a custom dependency resolver in my ASP.NET MVC 4 project in order to use Dependency injection framework.
What is the role of dependency resolver in ASP.NET MVC 4 ?
I am new to ASP.NET MVC 4. I have used a custom dependency resolver in my ASP.NET MVC 4 project in order to use Dependency injection framework.
What is the role of dependency resolver in ASP.NET MVC 4 ?
It allows you to abstract away from Dependency Injection implementation. Later if you decide to switch from Unity to Windsor, you can do it much easier without having to re-write lots of code
It means that you can resolve your instances using this code
DependencyResolver.Current.GetService<IMyController>();
I use a different approach using Ninject
Now I create a custom controller factory class (class derived from DefaultControllerFactory).My goal is to make MVC use my controller factory when it tries to create a controller object.
public class NinjectControllerFactory : DefaultControllerFactory
{
#region Member Variables
private IKernel ninjectKernel = null;
#endregion
public NinjectControllerFactory(IKernel kernel)
{
this.ninjectKernel = kernel;
AddBindings();
}
private void AddBindings()
{
//BO
ninjectKernel.Bind<IAuthenticationBO>().To<AuthenticationBO>();
//DAO
ninjectKernel.Bind<ISharedDAO>().To<SharedDAO>();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
}
}
Make MVC to use my custom controller factory. In Global.asax in Application_Start()
public class MvcApplication : System.Web.HttpApplication
{
private IKernel kernel = new StandardKernel();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//register a cutom controller factory
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
}
}
So now when MVC creates controller objects it uses our custom controller factory and as you saw it resolves all dependencies using Ninject.
For example
public class MainController : Controller
{
#region Member Variables
private IAuthenticationBO authentication = null;
#endregion
public MainController(IAuthenticationBO authentication)
{
this.authentication = authentication;
}
}
Ninject injects the implementation of IAuthenticationBO (in our case AuthenticationBO) and we can use it. Also it's very easy to use mocking and TDD, but it's beyond the scope of the question.
© 2022 - 2024 — McMap. All rights reserved.