autofac - 如何在不注册类型对象的情况下解决开放的通用服务?
问题描述
我试图弄清楚如何在不注册类型的情况下解决通用服务。我需要在运行时执行此操作,因为有太多不同的类型需要传递给该服务和其他几个。
我使用 RegisterAssemblyTypes 注册了几个服务。其中一项服务是 MongoService,它注册为 MongoService<>。
我看到范围注册列表中列出的服务。当我尝试将服务解析为
_productService = diScope.Resolve<MongoService<Product>>(new NamedParameter("mongoSettings", productCollection));
我得到下面的 ComponentNotRegisteredException:
Autofac.Core.Registration.ComponentNotRegisteredException
HResult=0x80131500
Message=The requested service 'RecWebEditor.Services.MongoService`1[
[bn.pds.ren.RENAPI.objects.ren.Product, RENAPI, Version=2020.2.4.8, Culture=neutral, PublicKeyToken=null]]'
has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(),
or use the ResolveOptional() method to resolve an optional dependency.
Source=Autofac
我知道 Autofac 没有注册 Product 类型,因为我没有注册它。
我希望这会以与 Microsoft Logging ILogger 相同的方式得到解决。
我怀疑我遗漏了一些明显的东西。
谢谢
解决方案
我认为这里有几点需要注意:
- 您无法解决未注册的问题。
- 截至今天(2021 年 2 月 2 日),您无法使用程序集扫描注册开放泛型。这是一个正在积极工作的公关,所以它来了,但它不在这里。
我认为答案将是:
MongoService<T>
不要使用程序集扫描进行注册,而是使用开放的泛型注册。它看起来像这样,但请阅读我链接的文档以获得更多理解。这是它可能看起来的示例,而不是为您的应用程序的需求准备好复制/粘贴。
builder.RegisterGeneric(typeof(MongoService<>))
.AsSelf();
之后,看看您是否可以解决您的MongoService<Product>
. 我不认为当您使用必须T
在MongoService<T>
.
如果您想查看更多真实代码,这里有一些示例单元测试显示了实际的通用注册。
推荐阅读
- office-js - Office 插件审核评论
- c# - 实体框架有一些表是唯一的,而另一些则根据客户端不同
- cmake - 使用 CTest/CMake 时在 VS2019 测试资源管理器中指定命名空间/类
- swiftui - 如何在 navigationBarItems 中对齐动态按钮
- angular - 在传单中查找距目标点最近的点
- android - 滚动视图不适用于android中的按钮
- scons - 构建 gem5 时出错:TypeError:文件 /hdd/Me/gem5/src/systemc/ext/systemc 找到预期的目录
- mysql - 这些凭据与我们的记录不匹配。在 Laravel 6 中
- postgresql - PostgreSQL 活动但不接受连接
- mysql - 如何查看 pandas read_csv() 中跳过的记录?