-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: optimize ScopedTimedBackgroundWorker implementation
- Loading branch information
1 parent
36d09d1
commit 691f57a
Showing
4 changed files
with
126 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
94 changes: 59 additions & 35 deletions
94
src/PallasBot.Domain/Abstract/ScopedTimedBackgroundWorker.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
src/PallasBot.Domain/Extensions/DependencyInjectionExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace PallasBot.Domain.Extensions; | ||
|
||
public static class DependencyInjectionExtensions | ||
{ | ||
public static TReturn RunInScope<TService, TReturn>(this IServiceProvider serviceProvider, Func<TService, TReturn> operation) | ||
where TService : notnull | ||
{ | ||
using var scope = serviceProvider.CreateScope(); | ||
var service = scope.ServiceProvider.GetRequiredService<TService>(); | ||
return operation.Invoke(service); | ||
} | ||
|
||
public static void AddScopedTimedBackgroundWorker<TWorker, TService>(this IServiceCollection services) | ||
where TWorker : class, IHostedService | ||
where TService : class | ||
{ | ||
services.AddScoped<TService>(); | ||
services.AddHostedService<TWorker>(); | ||
} | ||
} |