gpt4 book ai didi

c# - Autofac 未解析 ApiController 的类型和命名参数

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:50 26 4
gpt4 key购买 nike

我有三个不同的应用程序,它们都使用相同的业务层/数据层构建。我将 IUserNameProvider 添加到所有三个应用程序使用的 IUnitOfWork 类。因为每个应用程序使用不同的方法获取用户名,所以我创建了 IUserNameProvider 并使用 Autofac 注入(inject)适当的实现。

这看起来应该是相当简单的代码,但我无法为 Web API 应用程序正确配置它。类似的代码在控制台应用程序中运行良好

我的 Global.asax.cs

protected void Application_Start()
{
var builder = new ContainerBuilder();

builder.RegisterType<WebAPIGetUser>().As<SSEMPA.DataAccess.Infrastructure.IUserNameProvider>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>()
.WithParameter("connectionString", ConfigurationManager.ConnectionStrings["MyDataContex"].ConnectionString);

//other type registrations ...

DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));

// other registrations ....
}

我的 UnitOfWork 构造函数

public class UnitOfWork : IUnitOfWork
{
private MyDataContext dataContext;

public UnitOfWork(IUserNameProvider userNameProvider, string connectionString)
{
dataContext = new MyDataContext (connectionString, userNameProvider);
}

...
}

我的 API Controller

public class AgencyApiController : ApiController
{
private readonly IUnitOfWork _unitOfWork;

public AgencyApiController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}

...
}

当 API 被命中时,它会抛出以下错误:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>An error occurred when trying to create a controller of type 'AgencyApiController'. Make sure that the controller has a parameterless public constructor.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'SSEMPA.DataAccess.Infrastructure.UnitOfWork' can be invoked with the available services and parameters: Cannot resolve parameter 'SSEMPA.DataAccess.Infrastructure.IUserNameProvider userNameProvider' of constructor 'Void .ctor(SSEMPA.DataAccess.Infrastructure.IUserNameProvider , System.String)'.
</ExceptionMessage>
<ExceptionType>Autofac.Core.DependencyResolutionException</ExceptionType>

我尝试过为 IUserNameProvider 和连接字符串使用命名参数,但这并没有改变任何东西。看起来这应该可行,所以我一定是遗漏了一些小东西。

感谢您看到这里。

最佳答案

除了控制台应用程序之外,您还需要为 WebAPI 执行额外的配置和设置。查看此处的文档以获取说明:Autofac Web Api Integration

关于c# - Autofac 未解析 ApiController 的类型和命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com