RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.61k stars 1.22k forks source link

MSBuild is failing when adding Hangfire job #4873

Closed rodwin closed 2 months ago

rodwin commented 2 months ago

Error Severity Code Description Project File Line Suppression State Error NSwag command line tool for .NET Core Net80, toolchain v14.0.3.0 (NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0));Visit http://NSwag.org for more information.;NSwag bin directory: C:\Users\rodwin\.nuget\packages\nswag.msbuild\14.0.3\tools\Net80;Executing file 'config.nswag' with variables 'Configuration=Debug'...;Launcher directory: C:\Users\rodwin\.nuget\packages\nswag.msbuild\14.0.3\tools\Net80;System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.;---> System.InvalidOperationException: NSwag requires the assembly CBS.Intelplus.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null to have either an BuildWebHost or CreateWebHostBuilder/CreateHostBuilder method. See https://docs.microsoft.com/en-us/aspnet/core/fundamentals/hosting?tabs=aspnetcore2x for suggestions on ways to refactor your startup type.;at NSwag.Commands.ServiceProviderResolver.GetServiceProvider(Assembly assembly) in /_/src/NSwag.Commands/HostApplication.cs:line 87;at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in /_/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 27;at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor);at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span1 copyOfArgs, BindingFlags invokeAttr);--- End of inner exception stack trace ---;at System.Reflection.MethodBaseInvoker.InvokeDirectByRefWithFewArgs(Object obj, Span`1 copyOfArgs, BindingFlags invokeAttr);at System.Reflection.MethodBaseInvoker.InvokeWithFewArgs(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters);at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in //src/NSwag.AspNetCore.Launcher/Program.cs:line 132;System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.;at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in //src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:line 195;at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in //src/NSwag.Commands/NSwagDocumentBase.cs:line 270;at NSwag.Commands.NSwagDocument.ExecuteAsync() in //src/NSwag.Commands/NSwagDocument.cs:line 67;at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in //src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 76;at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in //src/NSwag.Commands/Commands/Document/ExecuteDocumentCommand.cs:line 33;at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input);at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input);at NSwag.Commands.NSwagCommandProcessor.ProcessAsync(String[] args) in /_/src/NSwag.Commands/NSwagCommandProcessor.cs:line 62 CBS.Intelplus.Web C:\Users\rodwin\source\Workspaces\CBS.Intelplus\src\Web\CBS.Intelplus.Web.csproj 84

`

Sample code

private static void AddBackgroundJobs(IServiceCollection services, IConfiguration configuration)
{
    services.AddScoped<IMyRecurringJob, MyRecurringJob>();

    services.Configure<OutboxOptions>(configuration.GetSection("Outbox"));

    services.AddHangfire(x => x
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(configuration.GetConnectionString("Database"), new SqlServerStorageOptions
        {
            PrepareSchemaIfNecessary = false,
            CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
            SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            QueuePollInterval = TimeSpan.Zero,
            UseRecommendedIsolationLevel = true,
            DisableGlobalLocks = true // Migration to Schema 7 is required,
        }));

    // Add the processing server as IHostedService
    services.AddHangfireServer(options =>
    {
        options.Queues = new[] { "loads", "default" };
        options.WorkerCount = 4;
    });

    RecurringJob.AddOrUpdate<IMyRecurringJob>("IMyRecurringJob", job => job.DoSomethingReentrant(), Cron.Hourly);

}

public interface IMyRecurringJob
{
    public void DoSomethingReentrant();
}
public class MyRecurringJob : IMyRecurringJob
{
    public void DoSomethingReentrant()
    {
        Console.WriteLine("IMyRecurringJob doing something");
    }
}

If I comment the line RecurringJob.AddOrUpdate<IMyRecurringJob>("IMyRecurringJob", job => job.DoSomethingReentrant(), Cron.Hourly);

Nswag works again.

Appreciate any help.

Thanks.

rodwin commented 2 months ago

After putting the RecurringJob.AddOrUpdate after the services have been build. e.g. in program.cs, it now works.

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    //await app.InitialiseDatabaseAsync();
}
else
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHealthChecks("/health");
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseHangfireDashboard("/jobs");

RecurringJob.AddOrUpdate("some-id", () => Console.WriteLine(), Cron.Minutely);

Closing this now.