I am pretty new to DI pattern. I was trying to implement DI in one of my controller classes. But the service is not resolved by Unity. Here is what I have done:
Using Unity.MVC5 package:I have the following class:
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<IProductServices, ProductServices>();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
I have registered my service in the above class.
next i called this class from global.asax as below:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
UnityConfig.RegisterComponents();
}
Following is my controller:
private readonly IProductServices productServices;
/// <summary>
/// Public constructor to initialize product service instance
/// </summary>
public ProductController(IProductServices p)
{
this.productServices = p;
}
When i run the application, it throws an error saying the "there is no parameterless constructor present". Am i doing something wrong? Any help will be appreciated. All the tutorials I have researched do the same thing.
UnityConfig.RegisterComponents();to the top of theApplication_Startso all your components are registered before anything else is happening - trailmax