简体   繁体   English

我可以为.NET Core DependencyInjection提供“解析器”以返回未注册任何服务的最小起订量吗?

[英]Can I provide the .NET Core DependencyInjection with a “resolver” to return a Moq of any service which isn't registered?

Given a class with a dependency: 给定一个具有依赖性的类:

class SomeService : ISomeService { ctor(ISomeDependency someDependency ... }

Using Moq I can mock out the dependency like this: 使用Moq,我可以像这样模拟依赖项:

var services = new ServiceCollection()
.AddTransient(_ => Mock.Of<ISomeDependency>())
.AddTransient<ISomeService,SomeService>()
.BuildServiceProvider();

services.GetRequiredService<ISomeService>(); 

Is there anyway I can register a "provider" which the ServiceProvider will use if an implementation isn't registered? 无论如何,如果未注册实现,我是否可以注册ServiceProvider将使用的“提供商”? I'd like the ServiceProvider to return a Mock.Of<T> if the dependency T hasn't been registered. 如果未注册依赖项T我希望ServiceProvider返回Mock.Of<T>

I want to do this because I have some classes lots of dependencies and want to avoid some typing. 我想要这样做是因为我有些类具有很多依赖关系,并且希望避免某些类型的输入。

Is there anyway I can register a "provider" which the ServiceProvider will use if an implementation isn't registered? 无论如何,如果未注册实现,我是否可以注册ServiceProvider将使用的“提供商”?

With Microsoft.Extensions.DependencyInjection (MS.DI) there isn't a way to do this. 使用Microsoft.Extensions.DependencyInjection(MS.DI),无法实现此目的。 What you're looking for is unregistered type resolution . 您正在寻找的是未注册的类型解析 Most mature DI Containers actually contain hooks that allow to intercept calls from the library when an unregistered type is requested. 大多数成熟的DI容器实际上都包含钩子,当请求未注册的类型时,这些钩子可以拦截来自库的调用。 But MS.DI, however, does not have such a feature. 但是,MS.DI没有这种功能。 All registrations must be made explicitly and there is no way around it. 必须明确进行所有注册,并且无法解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 .NET Core 控制台应用程序中使用 Microsoft.Extensions.DependencyInjection? - How can I use Microsoft.Extensions.DependencyInjection in an .NET Core console app? .Net Core 服务未注册 - .Net Core service is not getting registered azure 是否提供/提供任何 api 或任何我可以将自定义域添加到我的应用程序服务的方式? - Do azure provide/offer any api or any way from which i can add custom domain to my app service? 如何在Asp.net Core运行时从DependencyInjection解析通用类型服务 - How to resolve a generic type service from the DependencyInjection at Asp.net Core runtime .Net核心服务容器,我保证为界面注册最后一个服务吗? - .Net Core Service container, am I guaranteed to get last service registered for the interface? 无法使用布尔值在 .net core 3 上创建服务 - Can't create service on .net core 3 with boolean 无法获得Moq设置以不返回null - Can't get Moq Setup to not return null 无法让Moq返回值 - Can't get Moq to return a value 带有 xunit .NET Core 3.1 和 Moq 的工作单元的单元测试服务 - Unit Testing Service with Unit of Work with xunit .NET Core 3.1 and Moq ASP.NET Core 2+中的ILogger和DependencyInjection - ILogger and DependencyInjection in ASP.NET Core 2+
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM