Created
October 26, 2023 14:10
-
-
Save adamstirtan/ef6439b8373d492c86419fd1ddd557ca to your computer and use it in GitHub Desktop.
.NET console app using dependency injection and ILogger
This file contains hidden or 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
| using System; | |
| using Microsoft.Extensions.DependencyInjection | |
| using Microsoft.Extensions.Logging; | |
| namespace MyApp | |
| { | |
| internal class Program | |
| { | |
| private static void Main(string[] args) | |
| { | |
| var services = CreateServices(); | |
| Application app = services.GetRequiredService<Application>(); | |
| app.MyLogic(); | |
| } | |
| private static ServiceProvider CreateServices() | |
| { | |
| var serviceProvider = new ServiceCollection() | |
| .AddLogging(options => | |
| { | |
| options.ClearProviders(); | |
| options.AddConsole(); | |
| }) | |
| .AddSingleton<Application>(new Application()) | |
| .BuildServiceProvider(); | |
| return serviceProvider; | |
| } | |
| } | |
| public class Application | |
| { | |
| private readonly ILogger<Application> _logger; | |
| public Application(ILogger<Application> logger) | |
| { | |
| _logger = logger; | |
| } | |
| public void MyLogic() | |
| { | |
| _logger.LogInformation("Hello, World!"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment