亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Core 2.0 IServiceCollection 缺少 AddHostedService?

Core 2.0 IServiceCollection 缺少 AddHostedService?

C#
炎炎設計 2022-01-09 10:26:25
嘗試使用:啟動.cspublic void ConfigureServices(IServiceCollection services) {  services.AddHostedService<LifetimeEvents>();    .    .    .}LifeTimeEvents 類從 IHostedService 繼承。我收到此錯誤:'IServiceCollection' does not contain a definition for 'AddHostedService' and no extension method 'AddHostedService' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)我似乎找不到要使用的正確命名空間或要包含的 nuget 包以使其正常工作,但它在 .NET Core 2.1 中開箱即用,這在 .NET Core 2.0 中是否不可用?有什么辦法讓它工作嗎?更新:作為一種解決方法,我將代碼更改為使用:啟動.cspublic void ConfigureServices(IServiceCollection services) {  services.AddSingleton<LifetimeEvents>();    .    .    .}public void Configure(IApplicationBuilder appBuilder, IHostingEnvironment envHost, LifetimeEvents appEvents)  {  appEvents.StartAsync(new CancellationToken(false));    .    .    .}這似乎已經完成了這項工作。沒有回答我最初的問題,我不確定它是多么“最佳實踐”,但它確實讓我開始重構這個 .NET Core 2.0 應用程序。
查看完整描述

2 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

這只是在 .NET Core 2.0 中不可用嗎?


ServiceCollectionHostedServiceExtensions.AddHostedService(IServiceCollection) 方法如 API 參考中所示


適用于

ASP.NET Core

2.1


但是源代碼可以在 GitHub 上找到。您可以輕松地在那里查看并將本地版本復制到您的 2.0 項目


namespace Microsoft.Extensions.DependencyInjection

{

    public static class ServiceCollectionHostedServiceExtensions

    {

        /// <summary>

        /// Add an <see cref="IHostedService"/> registration for the given type.

        /// </summary>

        /// <typeparam name="THostedService">An <see cref="IHostedService"/> to register.</typeparam>

        /// <param name="services">The <see cref="IServiceCollection"/> to register with.</param>

        /// <returns>The original <see cref="IServiceCollection"/>.</returns>

        public static IServiceCollection AddHostedService<THostedService>(this IServiceCollection services)

            where THostedService : class, IHostedService

            => services.AddTransient<IHostedService, THostedService>();

    }

}


理想情況下,您可以將項目更新到 2.1,以便擴展可用。


查看完整回答
反對 回復 2022-01-09
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

我相信你正在尋找這個


https://blogs.msdn.microsoft.com/cesardelatorre/2017/11/18/implementing-background-tasks-in-microservices-with-ihostedservice-and-the-backgroundservice-class-net-core-2-x/


我對自己做了一個 2 小時自稱獲獎的黑客馬拉松,以了解這一點。


https://github.com/nixxholas/nautilus


您可以在此處參考注入并從那里實現摘要。


許多 MVC 項目并不真正需要操作持久的后臺任務。這就是為什么您看不到它們通過模板融入新項目的原因。最好為開發人員提供一個可以點擊并繼續使用的界面。


此外,關于為此類后臺任務打開該套接字連接,我還沒有為此建立解決方案。據我所知/所做的,我只能將有效負載廣播到連接到我自己的 socketmanager 的客戶端,所以你必須在別處尋找。如果 IHostedService 中有任何關于 websocket 的信息,我肯定會發出嗶嗶聲。


好吧,無論如何,這就是發生的事情。


把它放在你的項目中的某個地方,它更像是一個讓你重載以創建自己的任務的界面


/// Copyright(c) .NET Foundation.Licensed under the Apache License, Version 2.0.

    /// <summary>

    /// Base class for implementing a long running <see cref="IHostedService"/>.

    /// </summary>

    public abstract class BackgroundService : IHostedService, IDisposable

    {

        protected readonly IServiceScopeFactory _scopeFactory;

        private Task _executingTask;

        private readonly CancellationTokenSource _stoppingCts =

                                                       new CancellationTokenSource();


        public BackgroundService(IServiceScopeFactory scopeFactory) {

            _scopeFactory = scopeFactory;

        }


        protected abstract Task ExecuteAsync(CancellationToken stoppingToken);


        public virtual Task StartAsync(CancellationToken cancellationToken)

        {

            // Store the task we're executing

            _executingTask = ExecuteAsync(_stoppingCts.Token);


            // If the task is completed then return it,

            // this will bubble cancellation and failure to the caller

            if (_executingTask.IsCompleted)

            {

                return _executingTask;

            }


            // Otherwise it's running

            return Task.CompletedTask;

        }


        public virtual async Task StopAsync(CancellationToken cancellationToken)

        {

            // Stop called without start

            if (_executingTask == null)

            {

                return;

            }


            try

            {

                // Signal cancellation to the executing method

                _stoppingCts.Cancel();

            }

            finally

            {

                // Wait until the task completes or the stop token triggers

                await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite,

                                                              cancellationToken));

            }

        }


        public virtual void Dispose()

        {

            _stoppingCts.Cancel();

        }

    }

這是您實際使用它的方法


public class IncomingEthTxService : BackgroundService

    {

        public IncomingEthTxService(IServiceScopeFactory scopeFactory) : base(scopeFactory)

        {

        }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)

        {


            while (!stoppingToken.IsCancellationRequested)

            {

                using (var scope = _scopeFactory.CreateScope())

                {

                    var dbContext = scope.ServiceProvider.GetRequiredService<NautilusDbContext>();


                    Console.WriteLine("[IncomingEthTxService] Service is Running");


                    // Run something


                    await Task.Delay(5, stoppingToken);

                }

            }

        }

    }

如果你注意到了,那里有一個獎金。您必須使用服務范圍才能訪問數據庫操作,因為它是單例的。


注入你的服務


// Background Service Dependencies

            services.AddSingleton<IHostedService, IncomingEthTxService>();


查看完整回答
反對 回復 2022-01-09
  • 2 回答
  • 0 關注
  • 271 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號