AutoFac does not register api controller

2019-09-14 01:05发布

问题:

I am using AutoFac to registered api controller but don't know whats the problem

Getting error

Type 'myApp.WebAPI.Controllers.myController' does not have a default constructor

I added IocHelper class as below

public class IocHelper {
public static IContainer CreateContainer() {

        var builder = new ContainerBuilder();
        builder.RegisterControllers(Assembly.GetExecutingAssembly());
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        var container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        return container;
    }
} 

Thanks in advance.

回答1:

    Please refer the below solution, and also make sure you declared the injected interfaces as public explicitly.
    //Global.asax file -Application Start method
    protected void Application_Start()
    {
             var bootStrapApp = new BootstrapApplication()
            .ConfigureRoute(GlobalConfiguration.Configuration)
            .ConfigureContainer(new ContainerBuilder(), GlobalConfiguration.Configuration);
    }

    // BootstrapApplication.cs class file

    public class BootstrapApplication
    {
       public BootstrapApplication ConfigureRoute(HttpConfiguration httpConfiguration)
       {

          httpConfiguration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
          return this;
       }

      public BootstrapApplication ConfigureContainer(ContainerBuilder container, HttpConfiguration httpConfiguration)
      {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(n => n.FullName.StartsWith("<projectNamespacevalue>")).ToArray();
        //projectNamespacevalue for ex. AspNet.WebApi2.Demo 
        // var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(n => n.FullName.StartsWith("AspNet")).ToArray();

        container.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
        container.RegisterApiControllers(assemblies); //WebApi controllers scanning and registration
        var ioccontainer = container.Build();
        httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(ioccontainer);      
        return this;
    }
}