ASP.NET Core Web App DI 错误 - 某些服务无法构建(验证服务描述符时出错)

2023-11-22

我正在创建一个 ASP.NET Core Web 应用程序。我正在通过图书馆项目使用存储库。我在网络应用程序项目中引用了它。

存储库界面如下:

public interface IPushNotificationRepository
{
    IQueryable<PushNotification> Notifications
    {
        get;
    }
    IQueryable<Client> Clients
    {
        get;
    }

    void Add(PushNotification notification);
    void Add(Client client);
    void AddRange(IList<PushNotification> notifications);
    bool AddIfNotAlreadySent(PushNotification notification);
    void UpdateDelivery(PushNotification notification);
    bool CheckIfClientExists(string client);
    Client FindClient(int? id);
    void Update(Client client);
    void Delete(Client client);
}

在存储库中,我注入数据库上下文

    public class PushNotificationRepository : IPushNotificationRepository
    {
        private readonly PushNotificationsContext _context;

        public PushNotificationRepository(PushNotificationsContext context)
        {
            _context = context;
        }
}

启动类的服务配置如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddSingleton<IPushNotificationRepository, PushNotificationRepository>();
    services.AddDbContextPool<PushNotificationsContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PushNotificationsConnection")));
}

在控制器类中,我使用存储库:

    public class ClientsController : Controller
    {
        //private readonly PushNotificationsContext _context;
        private readonly IPushNotificationRepository _pushNotificationRepository;

        public ClientsController(IPushNotificationRepository pushNotificationRepository)
        {
            _pushNotificationRepository = pushNotificationRepository;
        }
}

存储库类位于一个单独的库项目中,该项目由 Web 应用程序项目引用。我收到的错误是:

System.AggregateException:“某些服务无法 构造(验证服务描述符时出错 '服务类型: Services.Messaging.Data.Abstract.IPushNotificationRepository 生命周期: 单例实现类型: Services.Messaging.Data.PushNotificationRepository':无法使用 范围服务“Services.Messaging.Data.PushNotificationsContext”来自 单例 'Services.Messaging.Data.Abstract.IPushNotificationRepository'。)'

非常感谢对此的一些建议


单例不能引用 Scoped 实例。错误信息很清楚。

无法使用范围服务 来自单例的“Services.Messaging.Data.PushNotificationsContext”

PushNotificationsContext 被视为有范围的服务。您几乎不应该从单例中使用作用域服务或瞬态服务。您还应该避免使用范围服务中的瞬态服务。使用范围服务注入您需要的内容是一个很好的做法,它会在请求后自动清理。

Either

services.AddTransient ();

or

services.AddScoped();

可以正常工作,但请检查您的设计。也许这不是您正在寻找的行为。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET Core Web App DI 错误 - 某些服务无法构建(验证服务描述符时出错) 的相关文章

随机推荐