我有三个不同的应用程序,它们都使用相同的业务层/数据层构建。我将 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/