如何在混合的Web API和MVC应用程序中使用Autofac解析Web API控制器? [英] How do I resolve Web API controllers using Autofac in a mixed Web API and MVC application?
问题描述
我有一个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控制器.简单控制器运行正常.
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屋!