我有三个不同的应用程序都使用相同的业务层/数据层构建。我正在将IUserNameProvider添加到所有三个应用程序使用的IUnitOfWork类中。因为每个应用程序使用不同的方法获取用户名,所以我创建了IUserNameProvider,并且我使用Autofac注入了相应的实现。
这似乎应该是相当简单的代码,但我无法为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);
}
...
}
我的ApiController
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和连接字符串使用命名参数,但这并没有改变任何东西。看起来这应该有效,所以我必须遗漏一些小事。
感谢您查看此内容。