gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:31:19 25 4
gpt4 key购买 nike

我正在使用依赖注入(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/

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