简体   繁体   English

.net core 3.1 HostBuilder 没有 RunAsServiceAsync 方法(IHostBuilder 不包含 RunAsServiceAsync 的定义)

[英].net core 3.1 HostBuilder not having RunAsServiceAsync method (IHostBuilder does not contain definition for RunAsServiceAsync)

I have .net core 3.1 console application and I want to run it as a windows service, my program.cs looks like我有 .net core 3.1 控制台应用程序,我想将它作为 Windows 服务运行,我的 program.cs 看起来像

public class Program
    {
        public static async Task Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            var builder = CreateHostBuilder(args);

            if (isService)
            {
                await builder.RunAsServiceAsync();
            }
            else
            {
                await builder.RunConsoleAsync();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseWindowsService()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker1>();
                    services.AddHostedService<Worker2>();
                });
    }

and the .csproj is而 .csproj 是

<Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UserSecretsId>dotnet-MyWorkerService-16487890-DF99-45C2-8DC4-5475A21D6B75</UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.16" />
    <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.16" />
  </ItemGroup>
</Project>

but for RunAsServiceAsync() error is coming like "IHostBuilder does not contain definition for RunAsServiceAsync"但是对于 RunAsServiceAsync() 错误就像“IHostBuilder 不包含 RunAsServiceAsync 的定义”一样

Can anyone please point to me where / what I am missing?任何人都可以指出我在哪里/我缺少什么吗?

RunAsServiceAsync appears to be 3rd party extension on IHostBuilder . RunAsServiceAsync似乎是第三方扩展IHostBuilder

It does not appear to be a built in function, native to .NET Core.它似乎不是 .NET Core 原生的内置函数。

I found an old implementation on GitHub here that you could probably implement yourself我发现在GitHub上的旧的实现在这里,你也许可以实现自己

public static class ServiceBaseLifetimeHostExtensions
{
    public static IHostBuilder UseServiceBaseLifetime(this IHostBuilder hostBuilder)
    {
        return hostBuilder.ConfigureServices((hostContext, services) => services.AddSingleton<IHostLifetime, ServiceBaseLifetime>());
    }

    public static Task RunAsServiceAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default)
    {
        return hostBuilder.UseServiceBaseLifetime().Build().RunAsync(cancellationToken);
    }
}

public class ServiceBaseLifetime : ServiceBase, IHostLifetime
{
    private TaskCompletionSource<object> _delayStart = new TaskCompletionSource<object>();

    public ServiceBaseLifetime(IApplicationLifetime applicationLifetime)
    {
        ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
    }

    private IApplicationLifetime ApplicationLifetime { get; }

    public Task WaitForStartAsync(CancellationToken cancellationToken)
    {
        cancellationToken.Register(() => _delayStart.TrySetCanceled());
        ApplicationLifetime.ApplicationStopping.Register(Stop);

        new Thread(Run).Start(); // Otherwise this would block and prevent IHost.StartAsync from finishing.
        return _delayStart.Task;
    }

    private void Run()
    {
        try
        {
            Run(this); // This blocks until the service is stopped.
            _delayStart.TrySetException(new InvalidOperationException("Stopped without starting"));
        }
        catch (Exception ex)
        {
            _delayStart.TrySetException(ex);
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        Stop();
        return Task.CompletedTask;
    }

    // Called by base.Run when the service is ready to start.
    protected override void OnStart(string[] args)
    {
        _delayStart.TrySetResult(null);
        base.OnStart(args);
    }

    // Called by base.Stop. This may be called multiple times by service Stop, ApplicationStopping, and StopAsync.
    // That's OK because StopApplication uses a CancellationTokenSource and prevents any recursion.
    protected override void OnStop()
    {
        ApplicationLifetime.StopApplication();
        base.OnStop();
    }
}

But it appears that this service based functionality is now built in when UseWindowsService is called on the builder.但是,当在构建器上调用UseWindowsService时,现在似乎内置了此基于服务的功能。

So in that case you would need to refactor your code accordingly to get the desired behavior因此,在这种情况下,您需要相应地重构代码以获得所需的行为

public class Program {
    public static async Task Main(string[] args) {
        var isService = !(Debugger.IsAttached || args.Contains("--console"));

        var builder = CreateHostBuilder(args);

        if (isService) {
            await builder.RunAsServiceAsync();
        } else {
            await builder.RunConsoleAsync();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)            
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker1>();
                services.AddHostedService<Worker2>();
            });
}

public static class ServiceBaseLifetimeHostExtensions {
    public static Task RunAsServiceAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default) {
        return hostBuilder.UseWindowsService().Build().RunAsync(cancellationToken);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .NET Core 3.1 - HostingEnvironment 不包含 MapPath 的定义 - .NET Core 3.1 - HostingEnvironment does not contain a definition for MapPath DirectoryEntry 不包含“属性”的定义(.NET CORE 3.1) - DirectoryEntry does not contain a definition for 'Properties' (.NET CORE 3.1) ASP.NET Core 3.1“‘用户’不包含‘FindFirstValue’的定义” - ASP.NET Core 3.1 "'User' does not contain a definition for 'FindFirstValue'" 网络核心:“ HttpContext”不包含“当前”的定义 - Net Core: 'HttpContext' does not contain a definition for 'Current'` Delegate在.net核心中不包含CreateDelegate的定义 - Delegate does not contain a definition for CreateDelegate in .net core .Net Core 2.0至2.1:“ IMutableEntityType”不包含“脚手架”的定义 - .Net Core 2.0 to 2.1: 'IMutableEntityType' does not contain a definition for 'Scaffolding' .NET Core 3.1 IHostBuilder Apache 使用 Kestrel Program.cs 设置托管 - .NET Core 3.1 IHostBuilder Apache Hosting With Kestrel Program.cs Setup 带有 MVC iapplicationbuilder 的 ASP.NET Core 不包含 usemvc 的定义 - ASP.NET Core with MVC iapplicationbuilder does not contain a definition for usemvc HttpResponse 不包含 Dot Net Core 中 BinaryWrite() 的定义 - HttpResponse does not contain a definition for BinaryWrite() in Dot Net Core http请求在.net core 2.1中不包含createresponse的定义 - http request does not contain a definition for createresponse in .net core 2.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM