[英]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.