为了账号安全,请及时绑定邮箱和手机立即绑定

无法从 Microsoft.Extensions.DependencyInjection.

无法从 Microsoft.Extensions.DependencyInjection.

C#
qq_遁去的一_1 2021-06-24 18:16:15
我正在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 herepublic interface IFooRepository{    string SomeMethod();}public class FooInMemoryRepository : IFooRepository{    public string SomeMethod() => "InMemory Foo";}public class FooOtherRepository : IFooRepository{    public string SomeMethod() => "Other Foo";}
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信