如何在混合 Web API 和 MVC 应用程序中使用 Autofac 解析 Web API 控制器? [英] How do I resolve Web API controllers using Autofac in a mixed Web API and MVC application?

查看:24
本文介绍了如何在混合 Web API 和 MVC 应用程序中使用 Autofac 解析 Web API 控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MVC 应用程序,我在其中定义了对 Web API 的一些依赖项.

Hi I have an MVC application where I have defined some dependencies to my Web API.

public class AutofacWebApiDependenceResolver : IDependencyResolver
{
    private readonly IComponentContext container;
    public AutofacWebApiDependenceResolver(IContainer container)
    {

     if (container == null)
     {
         throw new ArgumentNullException("container");
     }
     this.container = container;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType == null)
        {
            throw new ArgumentNullException("serviceType");
        }
        var ret = this.container.ResolveOptional(serviceType) ;
        return ret;
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {            
        if (serviceType == null)
        {
            throw new ArgumentNullException("serviceType");
        }            
        Type enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);
        var ret = (IEnumerable<object>)this.container.ResolveOptional(enumerableType);
        return ret;
    }
}

然后在我的引导程序类中,我在 Application_Start 中调用它,如下所示:

Then in my bootstrapper class I am calling it in Application_Start as follows:

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependenceResolver((IContainer)container);

当我调试代码时,我可以看到所有服务都注册到我的 DependencyResolver,但我仍然收到以下错误:

When I debug the code, I can see there are registrations of all services with my DependencyResolver, but I am still getting the following error:

发生错误.键入WebApp.Controllers.AuthenticateController"没有默认构造函数

An error has occurred.Type 'WebApp.Controllers.AuthenticateController' does not have a default constructor

这是我的控制器的代码:

Here is the code to my controller:

public class AuthenticateController : ApiController
{
    private readonly IFormsAuthenticationService formsAuthenticationService;
    private readonly IMemberShipProvider memberShip;
    private readonly IDataService dataService;

    public AuthenticateController(
        IMemberShipProvider memberShip,
        IFormsAuthenticationService formsAuthenticationService, IDataService dataService)
    {
        this.memberShip = memberShip;
        this.formsAuthenticationService = formsAuthenticationService;
        this.dataService= dataService;
     }

}

如何将参数带入 api 控制器.Simple 控制器工作正常.

How can I bring parameters to the api controllers. The Simple controllers are working fine.

推荐答案

nemesv 的指导解决了问题

nemesv's guidance did the trick

builder.RegisterApiControllers(Assembly.GetExecutingAssembly())

在调用 builder.Build()

这篇关于如何在混合 Web API 和 MVC 应用程序中使用 Autofac 解析 Web API 控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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