Web API does not accept parameters in constructor with Autofac

2

I've created an API to query client, this is my configuration:

public static class AutofacWebapiConfig
{
    public static IContainer Container;

    public static void Initialize(HttpConfiguration config)
    {
        Initialize(config, RegisterServices(new ContainerBuilder()));
    }

    public static void Initialize(HttpConfiguration config, IContainer container)
    {
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }

    private static IContainer RegisterServices(ContainerBuilder builder)
    {
        #region Application

        builder.RegisterType<ClienteAppService>().As<IClienteAppService>().InstancePerRequest();

        #endregion Application

        #region Domain Services

        #region

        builder.RegisterType<ClienteService>().As<IClienteService>().InstancePerRequest();

        #endregion

        #endregion Domain Services

        #region Data

        #region Context

        builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
        builder.RegisterType<SessionFactory>().As<ISessionFactory>().InstancePerRequest();

        #endregion Context

        #region Repositories

        #region Pessoas

        builder.RegisterType<ClienteRepository>().As<IClienteRepository>().InstancePerRequest();

        #endregion

        #endregion Repositories

        #endregion Data

        Container = builder.Build();
        return Container;
    }
}

public class Bootstrapper
{
    public static void Run()
    {
        // Configurar o AutoFac  
        AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
    }
}

Global.asax

  protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Bootstrapper.Run();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

ClientController

public class ClienteController : ApiController
{
    public readonly IClienteAppService _clienteAppService;

    public ClienteController(IClienteAppService clienteAppService)
    {
        _clienteAppService = clienteAppService;
    }

    // GET: api/Cliente/5
    public string Get(int id)
    {
        var cliente = _clienteAppService.GetCliente(id);
        return "value";
    }

    }
}

When I start my app and try to consult a client, it returns the following error:

  

An error occurred. It occurred   an error occurred trying to create a controller of type 'ClientController'.   Verify that the driver has a public constructor without parameters.      System.InvalidOperationException    in   System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create (HttpRequestMessage   request, HttpControllerDescriptor controllerDescriptor, Type   controllerType) in   System.Web.Http.Controllers.HttpControllerDescriptor.CreateController (HttpRequestMessage   request) in   System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext ()     An error has occurred.    The 'IMP.Api.Controllers.ClientController' type does not   has a default constructor   System.ArgumentException   in System.Linq.Expressions.Expression.New (Type type) in   System.Web.Http.Internal.TypeActivator.Create [TBase] (Type   instanceType) in   System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator (HttpRequestMessage   request, Type controllerType, Func'1 & activator) in   System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create (HttpRequestMessage   request, HttpControllerDescriptor controllerDescriptor, Type   controllerType)

It says that I need to have a public constructor to work, but if I create a public constructor how will I do to inject my interface into the constructor? ...

    
asked by anonymous 23.03.2018 / 15:17

1 answer

2

While reviewing the documentação , I saw that you skipped an important step, Controllers.

protected void Application_Start()
{
  var builder = new ContainerBuilder();

  // Get your HttpConfiguration.
  var config = GlobalConfiguration.Configuration;

  // Register your Web API controllers.
  builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

  // OPTIONAL: Register the Autofac filter provider.
  builder.RegisterWebApiFilterProvider(config);

  // OPTIONAL: Register the Autofac model binder provider.
  builder.RegisterWebApiModelBinderProvider();

  // Set the dependency resolver to be Autofac.
  var container = builder.Build();
  config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
    
23.03.2018 / 15:27