带有Web Api控制器的Autofac [英] Autofac with Web Api controller

查看:57
本文介绍了带有Web Api控制器的Autofac的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Autofac与WebApi控制器一起使用.我有:

I'm trying to use Autofac with WebApi controllers. I have :

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

这是我的AutofacConfig:

Here is my AutofacConfig:

 public class AutofacConfig
{       
    public static IContainer Container { get; private set; }
    public static void Register()
    {
        var builder = new ContainerBuilder();
        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        //Register repositories and services.            
        Container = builder.Build();
    }
}

然后我要设置DependencyResolver:

Then I'm trying to set DependencyResolver:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
        config.Filters.Add(new ExceptionHandlingAttribute());
        var container = AutofacConfig.Container;//I have registered controllers here!!!
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }
}

但是在请求期间,我收到:确保控制器具有无参数的公共构造函数".

But during the request I'm receiving : "Make sure that the controller has a parameterless public constructor".

我也尝试在AutofacConfig类中设置DependencyResolver,就像在教程

Also I've tried to set the DependencyResolver in the AutofacConfig class, just like in the tutorial

这是怎么了?

推荐答案

该错误消息表示您的控制器具有某些依赖关系,Autofac不知道该依赖关系如何为您注入它们.换句话说,控制器的构造函数具有一些需要注入的依赖项(参数),但是这些依赖项(服务)本身尚未在Autofac中注册.

The error message means that your controller has some dependencies that Autofac doesn't know how to inject them for you. In other words, your controller's constructor has some dependencies (parameters) that needs to be injected but those dependencies (services) themselves haven't been registered in Autofac.

如果您共享控制器的构造函数代码,我们将能够为您识别那些未注册的依赖项.

If you share your controller's constructor code we would be able to identify those unregistered dependencies for you.

这篇关于带有Web Api控制器的Autofac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆