Autofac with Web API 2 - Parameter-less constructor error

走远了吗. 提交于 2019-12-02 00:37:44

I found the issue, I was using HttpConfiguration to set the dependency resolver, it should have been GlobalConfiguration.Configuration.

So when I changed my line from:

config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

to

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

Everything started working.

Try registering the assemblies that have been loaded into the execution context of your application domain just before building your container:

var assemblies = AppDomain.CurrentDomain.GetAssemblies(); builder.RegisterAssemblyModules(assemblies);

/// <summary>
/// Configures Autofac DI/IoC
/// </summary>
/// <param name="app"></param>
/// <param name="config"></param>
private IContainer ConfigureInversionOfControl(IAppBuilder app, HttpConfiguration config)
{

    // Create our container
    var builder = new ContainerBuilder();

    // You can register controllers all at once using assembly scanning...
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    // Register our module
    builder.RegisterModule(new AutofacModule());

    // [!!!] ** Register assemblies of the current domain **
    var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    builder.RegisterAssemblyModules(assemblies);

    // Build
    var container = builder.Build();

    // Lets Web API know it should locate services using the AutofacWebApiDependencyResolver
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

    // Return our container
    return container;
}

And do not forget to have defined:

public class AutofacModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {

      ...

      builder.RegisterControllers(typeof(WebApiApplication).Assembly);
      builder.RegisterApiControllers(typeof(WebApiApplication).Assembly);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!