c# - WebApi DI Autofac - 确保 Controller 具有无参数公共(public)构造函数

标签 c# dependency-injection asp.net-web-api2 autofac unit-of-work

我正在使用依赖注入(inject)、借助存储库和 Autofac 作为容器的工作单元编写 Web API。依赖项在 24 小时前被完美地注入(inject),但是当我今天开始工作时突然间我一直收到错误

"Message": "An error has occurred.", "ExceptionMessage": "An error occurred when trying to create a controller of type 'SearchController'. Make sure that the controller has a parameterless public constructor.", "ExceptionType": "System.InvalidOperationException",

我将包括我的签名以及我如何注册类型,如果有人能指出我的代码可能出了什么问题,我将非常高兴。

在我的 web api Controller 上,我有

 private IUnitOfWork<Listing> _unitOfWork = null;
 public SearchController(IUnitOfWork<Listing> unitOfWork)
 {
     _unitOfWork = unitOfWork;
 }

工作单元采用通用类型参数来创建存储库。

在我的 WebApiConfig.cs 中,我正在注册如下类型

 builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
 builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>)).InstancePerDependency();
 builder.RegisterType(typeof(SearchController)).UsingConstructor(typeof(IUnitOfWork<Listing>));

我正在注册 SearchController 以使用接受 IUnitOfWork<> 的构造函数。在我添加 Mocked 单元测试之前一切正常,但出于某种目的我现在一直收到此错误。我还注册了 DependencyResolver

var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
config.DependencyResolver = resolver;

最佳答案

由于对这个问题有相当多的赞成票,但还没有任何答案,而且我不完全记得我是如何让它工作的,但我想分享在许多项目中一直完美运行的最新技术。

1) 这就是我注册通用存储库和工作单元的方式

 builder.RegisterType(typeof(YourContextInRepository));
 builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));
 builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>));

2) 这就是我为我的 WebAPI 设置依赖解析器的方式

// Set the dependency resolver for Web API.
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

3) 为 MVC Controller 注册它,

// Set MVC DI resolver to use our Autofac container
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

这种方法适用于 MVC 以及 WebAPI Controller ,我可以简单地做

private IUnitOfWork<Listing> _uow;
public SearchController(IUnitOfWork<Listing> uow)
{
    _uow = uow;
}

希望它对以后的人有所帮助。

关于c# - WebApi DI Autofac - 确保 Controller 具有无参数公共(public)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709710/

相关文章:

dependency-injection - 帮助开始使用 MEF

java - Spring Injection - 在构造函数中访问注入(inject)的对象

javascript - Angular 单元测试: Unknown provider: $$qProvider <- $$q <- $interval

angularjs - angularjs 应用程序和 Web api 2 中的 XSS

c# - 将带有字符串数组的 C# 结构传递给 c++ 函数,该函数接受 void * 用于 c# 结构和 char** 用于 c# 字符串数组

c# - 为什么泛型类型的表达式引用约束类型而不是运行时类型?

c# - 为什么我在这段代码上得到 "parameter is not valid"异常?

c# - 在多线程 C# 上运行的方法的扩展性能

c# - 可以通过 web api 传递整数列表,还是我必须使用字符串参数

rest - OAuth 2 端点 : Additional Fields?