首页 > 解决方案 > 如何在不注册类型对象的情况下解决开放的通用服务?

问题描述

我试图弄清楚如何在不注册类型的情况下解决通用服务。我需要在运行时执行此操作,因为有太多不同的类型需要传递给该服务和其他几个。

我使用 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 相同的方式得到解决。

我怀疑我遗漏了一些明显的东西。

谢谢

标签: autofacasp.net5

解决方案


我认为这里有几点需要注意:

我认为答案将是:

MongoService<T>不要使用程序集扫描进行注册,而是使用开放的泛型注册。它看起来像这样,但请阅读我链接的文档以获得更多理解。这是它可能看起来的示例,而不是为您的应用程序的需求准备好复制/粘贴。

builder.RegisterGeneric(typeof(MongoService<>))
       .AsSelf();

之后,看看您是否可以解决您的MongoService<Product>. 我不认为当您使用必须TMongoService<T>.

如果您想查看更多真实代码,这里有一些示例单元测试显示了实际的通用注册。


推荐阅读