Web API does not accept parameters in the constructor with Autofac

Asked

Viewed 328 times

2

I 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);
    }

Clientecontroller

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 customer, the following error returns to me:

An error has occurred. It has occurred an error when trying to create a 'Clientecontroller' controller. Make sure the controller 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 type 'IMP.Api.Controllers.Customerscontroller' does not has a standard builder System.Argumentexception in System.Linq.Expressions.Expression.New(Type type) in System.Web.Http.Internal.Typeactivator.Create[Tbase](Type type instanceType) in System.Web.Http.Dispatcher.Defaulthttpcontrolleractivator.Getinstanceoractivator(Httprequestmessage request, Type controllerType, Func`1 & Activator) on System.Web.Http.Dispatcher.Defaulthttpcontrolleractivator.Create(Httprequestmessage request, Httpcontrollerdescriptor controllerDescriptor, Type controllerType)

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

  • Have you tried creating a public constructor with no parameters to see if the error persists?

  • @Perozzo Constructor without parameters does not generate error, but my interface is null...

1 answer

2


When analyzing the documentação, saw that you skipped an important step, register the 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.