首页 > 解决方案 > Blazor:尝试激活 yyy 时无法解析类型 xx 的服务

问题描述

我已经阅读了许多关于同一主题的其他 SO 问题,但我找到的答案都不适用于我的案例。

我已经在我的 Startup.cs 中成功添加了 4 个服务,并且之前运行良好。然后我添加了第 5 个,现在我意识到有些东西坏了 - 没有任何服务工作。即使我完全删除了第 5 个,其他的现在也因相同的错误而损坏。

尝试激活时无法解析类型 xx 的服务

这是我的 Startup.cs ConfigureServices.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddStorage();
    services.AddSingleton<IMyLocalStorage, MyLocalStorage>();
    services.AddSingleton<IFrontEndService, FrontEndService>();
    services.AddSingleton<ISystemProvider, SystemProviderService>();
    services.AddSingleton<IAuthenticationService, AuthenticationService>();
}

这是我注意到错误的最后一个 AuthenticationService,但即使是以前工作的旧服务现在也失败了。

public interface IAuthenticationService
{
   // ... 
}

public class AuthenticationService : IAuthenticationService
{
    private readonly FrontEndService frontEndService;
    private readonly MyLocalStorage myLocalStorage;

    public AuthenticationService(FrontEndService frontEndService, MyLocalStorage myLocalStorage)
    {
        this.frontEndService = frontEndService;
        this.myLocalStorage = myLocalStorage;
    }

    // ...
}

服务很简单;一个接口,该接口的一个实现,然后在 Startup.cs 中添加。我无法弄清楚它为什么停止工作。

因此,如果我删除 IAuthenticationService,则错误会显示在 FrontEndService 中,然后抱怨 MyLocalStorage:

public interface IFrontEndService
{
    Task<T> GetAsync<T>(string requestUri);
}

public class FrontEndService : IFrontEndService
{
    private readonly HttpClient client;
    private readonly MyLocalStorage myLocalStorage;

    public FrontEndService(HttpClient client, MyLocalStorage myLocalStorage)
    {
         // ...
    }
}

public class MyLocalStorage : IMyLocalStorage
{
    public MyLocalStorage(LocalStorage storage)
    {
        this.storage = storage;
    }
}

我在这里想念什么?

标签: c#dependency-injectionblazor

解决方案


当您调用IServiceCollection诸如 之类的方法时.AddSingleton<IFrontEndService, FrontEndService>(),您是在对容器说:“每当您看到IFrontEndService依赖项时,就注入 . 的实例FrontEndService。” 现在,如果你看看你的AuthenticationService

public class AuthenticationService : IAuthenticationService
{
    private readonly FrontEndService frontEndService;
    private readonly MyLocalStorage myLocalStorage;

    public AuthenticationService(FrontEndService frontEndService, MyLocalStorage myLocalStorage)
    {
        this.frontEndService = frontEndService;
        this.myLocalStorage = myLocalStorage;
    }

    // ...
}

请注意您是如何传递 and 的依赖项的FrontEndServiceMyLocalStorage而不是您注册的接口。这意味着容器无法识别它们,因此它不知道如何实现依赖图。

您需要更改服务以依赖接口,因为这些是您在容器中注册的内容:

public class AuthenticationService : IAuthenticationService
{
    private readonly IFrontEndService frontEndService;
    private readonly IMyLocalStorage myLocalStorage;

    public AuthenticationService(IFrontEndService frontEndService, IMyLocalStorage myLocalStorage)
    {
        this.frontEndService = frontEndService;
        this.myLocalStorage = myLocalStorage;
    }

    // ...
}

推荐阅读