简体   繁体   中英

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:

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? I'd like the ServiceProvider to return a Mock.Of<T> if the dependency T hasn't been registered.

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?

With Microsoft.Extensions.DependencyInjection (MS.DI) there isn't a way to do this. 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. But MS.DI, however, does not have such a feature. All registrations must be made explicitly and there is no way around it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM