Skip to content

Instantly share code, notes, and snippets.

@cyptus
Last active October 25, 2019 07:31
Show Gist options
  • Save cyptus/1c4d5d2c0f848cd577a7464738625eb1 to your computer and use it in GitHub Desktop.
Save cyptus/1c4d5d2c0f848cd577a7464738625eb1 to your computer and use it in GitHub Desktop.
C# Azure WebJob v3

create Console App (net core 2.1)

Install-Package Microsoft.Azure.WebJobs -Version 3.0.5
Install-Package Microsoft.Azure.WebJobs.Extensions -Version 3.0.2
Install-Package Microsoft.Azure.WebJobs.Extensions.Storage -Version 3.0.4
Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.2
Install-Package Microsoft.Extensions.Configuration.CommandLine -Version 2.2.0
Install-Package Microsoft.Extensions.DependencyInjection -Version 2.2.0
Install-Package Microsoft.Extensions.Logging.Console -Version 2.2.0
Install-Package Microsoft.Extensions.Options -Version 2.2.0
Install-Package Microsoft.Extensions.Options.ConfigurationExtensions -Version 2.2.0

Docs:
https://docs.microsoft.com/en-us/azure/app-service/webjobs-sdk-get-started
https://docs.microsoft.com/en-us/azure/app-service/webjobs-sdk-how-to

Set appsettings json files "Copy to Output Directory" to "always"
Set run.cmd files "Copy to Output Directory" to "always" and Encoding to UTF-8 (not UTF-8-BOM which is Visual Studios default!)

{
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=dev;Trusted_Connection=True;MultipleActiveResultSets=true;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace WebJobs
{
public class JobStartup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder.Services
.AddScoped(typeof(IFileRepository), typeof(FileRepository))
.AddScoped(typeof(IMyService), typeof(MyService))
.AddScoped<MyHandler>();
}
}
}
using Microsoft.Azure.WebJobs;
using System.Threading.Tasks;
namespace WebJobs
{
public class MyHandler
{
public IFileRepository Files { get; }
public IMyService MyService { get; }
public MyHandler(
IMyService myService,
IFileRepository files
)
{
Files = files;
MyService = myService;
}
public async Task HandleQueue([QueueTrigger("myqueue")] MyQueueDto item)
{
//...
}
public void HandleTimer([TimerTrigger("0 */1 * * * *", RunOnStartup = true)] TimerInfo timerInfo)
{
Console.WriteLine("hit at {0}", DateTime.UtcNow.ToLongTimeString());
}
}
}
using System.Threading.Tasks;
namespace WebJobs
{
public class Program
{
private static async Task Main(string[] args)
{
using (var job = new WebJob(args).Configure<JobStartup>())
{
await job.Start();
}
}
}
}
dotnet MyWebJob.dll
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading.Tasks;
namespace WebJobs
{
public class WebJob : IDisposable
{
public HostBuilder HostBuilder { get; protected set; }
public string[] CommandLineArgs { get; protected set; }
public Task Job { get; protected set; }
public WebJob(string[] args)
{
this.HostBuilder = new HostBuilder();
this.CommandLineArgs = args;
}
public Task Start()
{
this.Job = this.HostBuilder
.Build()
.RunAsync();
return Job;
}
public WebJob Configure<T>() where T : IWebJobsStartup
{
this.HostBuilder
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((context, builder) => builder
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(this.CommandLineArgs)
.Build()
)
.ConfigureLogging((context, builder) => builder
.AddConfiguration(context.Configuration.GetSection("Logging"))
.AddConsole()
)
.ConfigureWebJobs(x => x
.AddAzureStorageCoreServices()
.AddAzureStorage(queuesOptions => queuesOptions.MaxPollingInterval = TimeSpan.FromSeconds(10))
.AddTimers()
.UseWebJobsStartup(typeof(T))
)
.ConfigureServices((context, collection) => collection
.AddDbContext<CoreDbContext>(o => o
.UseSqlServer(
context.Configuration.GetConnectionString("DefaultConnection")
)
.ConfigureWarnings(warnings => warnings.Log(RelationalEventId.QueryClientEvaluationWarning))
)
.AddScoped<WebJobServiceActivator>()
//.AddScoped<ISettingSupplier, SettingSupplier>()
//...
)
.UseConsoleLifetime();
return this;
}
public void Dispose()
{
this.Job.Dispose();
}
}
}
using Microsoft.Azure.WebJobs.Host;
using System;
namespace WebJobs
{
public class WebJobServiceActivator : IJobActivator
{
private readonly IServiceProvider _service;
public WebJobServiceActivator(IServiceProvider service)
{
_service = service;
}
public T CreateInstance<T>()
{
return (T)_service.GetService(typeof(T));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment