I want to rewrite my current webjobs config to the version 3.0 but I can't get it to work with the documentation because I have no idea how to set the dashboardconnectionstring
or storageconnectionstring
without a config file.
JobHostConfiguration config = new JobHostConfiguration
{
NameResolver = new WebJobsNameResolver()
};
string defaultStorageConnectionString = string.Format( "Some dynamically generation string" );
config.DashboardConnectionString = defaultStorageConnectionString;
config.StorageConnectionString = defaultStorageConnectionString;
using(JobHost host = new JobHost(config))
{
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
I want to make it run continuously with the correct storage and dashboard connection string, without using a config file.
The 3.0.0 NuGet package update (non-beta) brought breaking changes. It's based on the generic host which is similar to the asp.net host. You could refer to the steps as below:
1.Add this line of code in your program.cs.
.ConfigureAppConfiguration((context, config) => {
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
The whole code in Program.cs.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebJob1template
{
class Program
{
static void Main()
{
var builder = new HostBuilder()
.UseEnvironment("Development")
.ConfigureAppConfiguration((context, config) => {
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureWebJobs(
b =>
{
b.AddAzureStorageCoreServices()
.AddAzureStorage()
.AddTimers()
.AddFiles();
//.AddDashboardLogging();
})
.ConfigureLogging((context, b) =>
{
b.SetMinimumLevel(LogLevel.Debug);
b.AddConsole();
})
.UseConsoleLifetime();
var host = builder.Build();
using (host)
{
host.Run();
}
}
}
}
2.Set appsettings.json
(note that set it's property Copy to Output Directory
or Copy always
):
{
"ConnectionStrings": {
"AzureWebJobsDashboard": "xxxx",
"AzureWebJobsStorage": "xxxx"
}
}
3.Functions.cs:
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
namespace WebJob1template
{
public class Functions
{
public static void ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger log)
{
//log.WriteLine(message);
log.LogInformation(message);
}
}
}
4.The output:
For more details, you could refer to this tutorial.
Update:
As Joey said, we could use
config.AddInMemoryCollection(settings);
with
public static Dictionary<string, string> settings = new Dictionary<string, string>
{
{"ConnectionStrings:AzureWebJobsDashboard:0", "xxxxxxx"},
{"ConnectionStrings:AzureWebJobsStorage:1", "xxxxxx"},
};
So that it will not use the config file. Here is the article about how to use AddInMemoryCollection