2
我已經全部建立具有相同業務層/數據層三個不同的應用程序。我將IUserNameProvider添加到所有三個應用程序使用的IUnitOfWork類中。因爲每個應用程序都使用不同的方法獲取用戶名,所以我創建了IUserNameProvider,並使用Autofac注入適當的實現。Autofac不分解式和命名參數ApiController
這似乎是它應該是相當簡單的代碼,但我不能讓它正確的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和連接串都命名參數嘗試過,但沒有任何改變。這似乎應該工作,所以我必須錯過一些小事。
感謝您看這個。
謝謝!其他人對此進行了配置,並且不在該項目中。我不知道是否已經有另一個配置。 – 2014-10-12 09:22:13