2
votes

I am using Unity to do dependency injection in ASP.Net MVC by creating a custom controller activator class as,

 public class CustomControllerActivator : IControllerActivator
{
    public IController Create(RequestContext requestContext, Type controllerType)
    {
        var controller = default(IController);
        if (controllerType != default(Type))
        {
            controller = ServiceLocator.Current.GetInstance(controllerType) as IController;
        }
        return controller;
    }
}

and then a custom dependency controller resolver class as follows,

 public class CustomControllerDependencyResolver : IDependencyResolver
{
    public object GetService(Type serviceType)
    {
        var resolvedObject = default(object);
        if (serviceType == typeof(IControllerActivator))
        {
            resolvedObject = new CustomControllerActivator();
        }

        return resolvedObject;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        var resolvedObjects = default(IEnumerable<Object>);

        resolvedObjects = ServiceLocator.Current.GetInstances(serviceType);
        return resolvedObjects;
    }
}

then I add the following line to global.asax.cs file,

DependencyResolver.SetResolver(new CustomControllerDependencyResolver());

to register my custom dependency resolver.

The above method holds good for MVC controllers but when I used to do the same for webapi controllers it fails as , An error occurred when trying to create a controller of type 'CustomerController'. Make sure that the controller has a parameterless public constructor.

1
You're using the wrong IDependencyResolver. You need to use System.Web.Http.Dependencies.IDependencyResolver. See asp.net/web-api/overview/advanced/dependency-injection - haim770
Seems I need to maintain another class which implements HTTP's IDependencyResolver. Is there any way where both controllers activation can co-exist like a single container can serve both the requirements. - Zafar
@Zafar - you could implement both System.Web.Http.Dependencies.IDependencyResolver and System.Web.Mvc.IDependencyResolver in the same class. - NightOwl888

1 Answers

0
votes

The problem is that the MVC and Webapi are working by their own DI so it creates object from the constructor of the controller which must be pram-less, but when you trying to make your own param constructor which will depend on your DI, you will need to install the configs which learn MVC or Webapi to handle your DI in your case you are using Unity so you have to install unity.webapi and this is the code :

PM> Install-Package Unity.WebAPI -Version 0.10.0