File tree Expand file tree Collapse file tree 3 files changed +55
-0
lines changed
docs/core/extensions/snippets/hosts Expand file tree Collapse file tree 3 files changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ using Microsoft . Extensions . Logging ;
2
+
3
+ internal sealed class JobRunner ( ILogger < JobRunner > logger )
4
+ {
5
+ public async Task RunAsync ( )
6
+ {
7
+ logger . LogInformation ( "Starting job..." ) ;
8
+
9
+ // Simulate work
10
+ await Task . Delay ( 1000 ) ;
11
+
12
+ // Simulate failure
13
+ // throw new InvalidOperationException("Something went wrong!");
14
+
15
+ logger . LogInformation ( "Job completed successfully." ) ;
16
+ }
17
+ }
Original file line number Diff line number Diff line change
1
+ using Microsoft . Extensions . DependencyInjection ;
2
+ using Microsoft . Extensions . Hosting ;
3
+ using Microsoft . Extensions . Logging ;
4
+
5
+ var builder = Host . CreateApplicationBuilder ( args ) ;
6
+ builder . Services . AddSingleton < JobRunner > ( ) ;
7
+
8
+ using var host = builder . Build ( ) ;
9
+
10
+ try
11
+ {
12
+ var runner = host . Services . GetRequiredService < JobRunner > ( ) ;
13
+
14
+ await runner . RunAsync ( ) ;
15
+
16
+ return 0 ; // success
17
+ }
18
+ catch ( Exception ex )
19
+ {
20
+ var logger = host . Services . GetRequiredService < ILogger < Program > > ( ) ;
21
+
22
+ logger . LogError ( ex , "Unhandled exception occurred during job execution." ) ;
23
+
24
+ return 1 ; // failure
25
+ }
Original file line number Diff line number Diff line change
1
+ <Project Sdk =" Microsoft.NET.Sdk.Worker" >
2
+
3
+ <PropertyGroup >
4
+ <TargetFramework >net9.0</TargetFramework >
5
+ <Nullable >enable</Nullable >
6
+ <ImplicitUsings >true</ImplicitUsings >
7
+ <RootNamespace >ShortLived.App</RootNamespace >
8
+ </PropertyGroup >
9
+
10
+ <ItemGroup >
11
+ <PackageReference Include =" Microsoft.Extensions.Hosting" Version =" 9.0.4" />
12
+ </ItemGroup >
13
+ </Project >
You can’t perform that action at this time.
0 commit comments