Good day i am writing an applicaiton that needs to read data from an Azure service bus topic. The registration function looks like this(see below). I would like to run this once on startup of The Asp.net Core application.
What would a good way to call this function since it seems IStartupFilter does not support async functions?
Any help would be greatly appreciated
async Task RegisterForMessages()
{
subscriptionClient = new SubscriptionClient(constring, TopicName, SubscriptionName);
// Register subscription message handler and receive messages in a loop
RegisterOnMessageHandlerAndReceiveMessages();
await subscriptionClient.CloseAsync();
}
Have you tried creating interface base approach for registering Async function like below:
public interface IStartupAction
{
Task ExecuteAsync(CancellationToken cancellationToken = default);
}
And a method for registering startup tasks with the DI container:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddStartupTask<T>(this IServiceCollection services)
where T : class, IStartupTask
=> services.AddTransient<IStartupAction, T>();
}
Finally, we add an extension method that finds all the registered IStartupAction
on app startup, runs them in order, and then starts the IWebHost
:
public static class StartupTaskWebHostExtensions
{
public static async Task RunWithTasksAsync(this IWebHost webHost, CancellationToken cancellationToken = default)
{
// Load all tasks from DI
var startupTasks = webHost.Services.GetServices<IStartupAction>();
// Execute all the tasks
foreach (var startupTask in startupTasks)
{
await startupTask.ExecuteAsync(cancellationToken);
}
// Start the tasks as normal
await webHost.RunAsync(cancellationToken);
}
}
For detailed steps , you can refer this doc.
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.