1
votes

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.

1
Try moving UnityConfig.RegisterComponents(); to the top of the Application_Start so all your components are registered before anything else is happening - trailmax
Thanks for your response. But unfortunately that didn't work. - Prajat Padhi
What do you mean with 'When i run the application'? What exactely is the error message / exception / stack trace? Which class should have a parameterless ctor? - nilsK
The error was thrown when it was trying to initialize the product controller. - Prajat Padhi
maybe it is caused by the service cannot be resolved from the resolver. are you sure that your service can be resolved from the resolver? if the service can not be resolved from the resolver, mvc will try to call the default constructor by reflection. - zhimin

1 Answers

2
votes

I finally found the reason. I was trying to implement unity in a Web API project using unity.mvc hoping that it would be the same. The error was resolved after the installed the unity.Asp.webapi package. Silly me.