Autofac-确保控制器具有无参数的公共构造函数 [英] Autofac - Make sure that the controller has a parameterless public constructor

查看:499
本文介绍了Autofac-确保控制器具有无参数的公共构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前已经有人问过它了-我问的原因是(我想)我尝试了所有建议的解决方案,但仍然无法解决.

I know it's been asked and answered before - the reason I'm asking is because (I think) I tried all suggested solutions to this problem but still can't resolve it.

我有一个ASP.NET Web API 2.0项目.我安装了AutofacAutofac.Mvc5Autofac.WebApi2依赖项.当我尝试调用API控制器时,出现以下错误:

I have an ASP.NET Web API 2.0 project. I have Autofac, Autofac.Mvc5 and Autofac.WebApi2 dependencies installed. When I try to call an API controller I get the following error:

尝试创建类型为'MyController'的控制器时发生错误.确保控制器具有无参数的公共构造函数.

An error occurred when trying to create a controller of type 'MyController'. Make sure that the controller has a parameterless public constructor.

在我的Global.asax中,我有一个呼叫IocConfig.Config()的呼叫,该呼叫已放置在App_Start中:

In my Global.asax I have a call to IocConfig.Config() which I have placed inside App_Start:

public static class IocConfig
{
    public static void Config()
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<MyLogger>().As<IMyLogger>();

        builder.RegisterApiControllers(Assembly.GetCallingAssembly());
        builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

        WebApiApplication.Container = builder.Build();

        DependencyResolver.SetResolver(
            new AutofacDependencyResolver(WebApiApplication.Container));
        GlobalConfiguration.Configuration.DependencyResolver =
             new AutofacWebApiDependencyResolver(WebApiApplication.Container);
    }
}

这是MyController的构造函数:

public MyController(IMyLogger logger)

当我尝试调用它时,出现关于构造函数的指定错误.我想念什么?

When I try to call it I get the specified error about the constructor. What am I missing?

推荐答案

我也遇到了此错误,根本原因是Controller的依赖项之一未在Autofac中正确注册.

I encountered this error as well and the root cause was that one of the Controller's dependencies wasn't registered correctly in Autofac.

InnerException包含详细信息(在我的情况下为Autofac.Core.DependencyResolutionException),并且ExceptionMessage包含此依赖项的详细信息.遵循以下原则:

The InnerException has the detail (in my case it was an Autofac.Core.DependencyResolutionException) and the ExceptionMessage included the detail of this dependency. Along the lines of:

激活特定注册时发生错误...无法解析参数'XXXX'

"An error occurred during the activation of a particular registration... Cannot resolve parameter 'XXXX'

这篇关于Autofac-确保控制器具有无参数的公共构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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