31

Hi I have an MVC application where I have defined some dependencies to my Web API.

public class AutofacWebApiDependenceResolver : IDependencyResolver
{
    private readonly IComponentContext container;
    public AutofacWebApiDependenceResolver(IContainer container)
    {

     if (container == null)
     {
         throw new ArgumentNullException("container");
     }
     this.container = container;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType == null)
        {
            throw new ArgumentNullException("serviceType");
        }
        var ret = this.container.ResolveOptional(serviceType) ;
        return ret;
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {            
        if (serviceType == null)
        {
            throw new ArgumentNullException("serviceType");
        }            
        Type enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
        var ret = (IEnumerable<object>)this.container.ResolveOptional(enumerableType);
        return ret;
    }
}

Then in my bootstrapper class I am calling it in Application_Start as follows:

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependenceResolver((IContainer)container);

When I debug the code, I can see there are registrations of all services with my DependencyResolver, but I am still getting the following error:

An error has occurred.Type 'WebApp.Controllers.AuthenticateController' does not have a default constructor

Here is the code to my controller:

public class AuthenticateController : ApiController
{
    private readonly IFormsAuthenticationService formsAuthenticationService;
    private readonly IMemberShipProvider memberShip;
    private readonly IDataService dataService;

    public AuthenticateController(
        IMemberShipProvider memberShip,
        IFormsAuthenticationService formsAuthenticationService, IDataService dataService)
    {
        this.memberShip = memberShip;
        this.formsAuthenticationService = formsAuthenticationService;
        this.dataService= dataService;
     }

}

How can I bring parameters to the api controllers. The Simple controllers are working fine.

Maslow
  • 18,464
  • 20
  • 106
  • 193
progrAmmar
  • 2,606
  • 4
  • 29
  • 58
  • have you registered your controllers with calling `builder.RegisterApiControllers(Assembly.GetExecutingAssembly());`? – nemesv Oct 14 '14 at 10:20
  • take look at this: http://stackoverflow.com/questions/9450282/autofac-and-asp-net-web-api-apicontroller – freshbm Oct 14 '14 at 10:23
  • @freshbm Yes I saw that, didn't get the solution :-S – progrAmmar Oct 14 '14 at 10:28
  • @nemesv I am unable to call builder.RegisterApiControllers(), can you please tell me which namespace do I have to import for that? – progrAmmar Oct 14 '14 at 10:28
  • The method builder.RegisterApiControllers is comes with the WebApi integration package https://code.google.com/p/autofac/wiki/WebApiIntegration – nemesv Oct 14 '14 at 10:32
  • @nemesv I tried that, `GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependenceResolver((IContainer)container); builder.RegisterApiControllers(Assembly.GetExecutingAssembly());' Still the same... – progrAmmar Oct 14 '14 at 10:38
  • 3
    you need to call `builder.RegisterApiControllers` before calling `builder.Build()`... – nemesv Oct 14 '14 at 10:44
  • Are you using Web API or MVC? The question is tagged MVC and the title says MVC but the contents of the question are around Web API. – Travis Illig Oct 14 '14 at 18:03
  • @TravisIllig I am using the WebApi in my MVC application – progrAmmar Oct 14 '14 at 23:46
  • Please refer this link.. http://stackoverflow.com/questions/30734251/autofac-does-not-register-api-controller/40277456#40277456 – Vishwa G Oct 27 '16 at 06:20
  • // Please refer the link might be helpful... http://stackoverflow.com/questions/30734251/autofac-does-not-register-api-controller/40277456#40277456 – Vishwa G Oct 27 '16 at 06:24

2 Answers2

69

I would suggest the following to make this work in your application with both MVC and WebApi.

First your project will need to have references to the following

  • Autofac
  • Autofac.WebApi
  • Autofac.Mvc5 (change the number at the end to match your aspnet mvc version)

Then in your Autofac registration you would need the following which will Register both MVC and WebApi Controllers and any other registrations you require. Then attach the Container to both the MVC DI and the WebApi DI.

var builder= new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly()); //Register MVC Controllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
//Register any other components required by your code....

var container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolver
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver

I hope this helps.

tstojecki
  • 1,480
  • 2
  • 19
  • 29
jonhoare
  • 1,279
  • 7
  • 15
  • 6
    `GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container);` That is the killer bit in my case. – droidbot Feb 15 '16 at 10:09
  • 3
    This sorted it out for me thanks! I also realised I had installed the wrong nuget package as I was using WebApi2. So once I had remove Autofac.WebApi and installed Autofac.WebApi2 it all worked like a charm, thanks @jonhoare – zanther Apr 18 '17 at 15:13
  • I soooo needed that! – Ayo Adesina Aug 03 '17 at 16:52
  • 3
    For newbies: code from @jonhoare answer you should put in `App_Start/WebApiConfig.cs` in `Register` method. – 1_bug May 28 '18 at 08:52
  • 1
    @Jennet. TY! this was my final problem, not having the Autofac.WebAPI2 installed. soon as that was installed, everything fell into place. thx! – Kakoritz Oct 18 '18 at 16:08
  • Where does the above code go? @1_bug, how do we put this in `WebApiConfig.cs`? We don't have a reference to `container` there. Thanks. – Alex May 16 '20 at 17:43
8

nemesv's guidance did the trick

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())

Calling builder.RegisterApiControllers before calling builder.Build()

huysentruitw
  • 27,376
  • 9
  • 90
  • 133
progrAmmar
  • 2,606
  • 4
  • 29
  • 58