我正在IFoo向Microsoft.Extensions.DependencyInjection服务注册一个接口 ( ),如下所示:
servicesBuilder.AddSingleton<IFooRepository, FooInMemoryRepository>();
当我解决依赖关系时,我几乎完全不知道具体类型:
services.GetRequiredService<IFooRepository>()
在这种情况下,一切正常。然而,在极少数情况下,我需要具体的实现 ( FooInMemoryRepository),所以我想直接解决这个问题。我试着打电话
services.GetRequiredService<FooInMemoryRepository>()
但是,这会引发异常:
System.InvalidOperationException: No service for type 'UserQuery+FooInMemoryRepository' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at UserQuery.Main() in C:\Users\User\AppData\Local\Temp\LINQPad5\_ntmafjyh\query_eecehy.cs:line 37
示例代码(LINQPad):
void Main()
{
var servicesBuilder = new ServiceCollection();
servicesBuilder.AddSingleton<IFooRepository, FooInMemoryRepository>();
servicesBuilder.AddSingleton<IFooRepository, FooOtherRepository>();
var services = servicesBuilder.BuildServiceProvider();
try
{
var foos = services.GetServices<IFooRepository>();
foreach(var foo in foos)
{
Console.WriteLine(foo.SomeMethod());
}
var ifoo = services.GetRequiredService<IFooRepository>();
Console.WriteLine(ifoo.SomeMethod());
var inMemoryRepo = services.GetRequiredService<FooInMemoryRepository>();
Console.WriteLine(inMemoryRepo.SomeMethod());
}
catch(InvalidOperationException ioex)
{
Console.WriteLine(ioex.ToString());
}
}
// Define other methods and classes here
public interface IFooRepository
{
string SomeMethod();
}
public class FooInMemoryRepository : IFooRepository
{
public string SomeMethod() => "InMemory Foo";
}
public class FooOtherRepository : IFooRepository
{
public string SomeMethod() => "Other Foo";
}
相关分类