I got tired of figuring this out everytime I had a play with something in a console application. DI is a great pattern to understand and use even when just having a play.
Refactor Program.cs to have Program as public and have a constructor to accept instantiated objects.
Add a public Run() method to execute your service code. This will run after the dependency injection container has been built.
In Main which is the console applications entry point, create the host and run the program. Here call CreateHostBuilder which will return an IHost which contains all of the services.
publicvoidRun() { _logger.LogInformation("Program is running."); _serviceA.DoSomething(); _logger.LogInformation("Program is completed."); }
staticvoidMain(string[] args) { var host = CreateHostBuilder(args).Build(); host.Services.GetRequiredService<Program>().Run(); } }
This would then output our logs which is expected.
1 2 3 4 5 6
info: ConsoleAppDependencyInjection.Program[0] Program is running. info: ConsoleAppDependencyInjection.ServiceB[0] Service B is doing something. info: ConsoleAppDependencyInjection.Program[0] Program is completed.
using Microsoft.Extensions.DependencyInjection; using System;
namespaceRedisDemo { internalstaticclassContainerConfiguration { publicstatic IServiceProvider Configure() { var services = new ServiceCollection();
// this is a convenience method from `Extensions.DependencyInjection` for distributed redis cache services.AddDistributedRedisCache(option => { option.Configuration = "localhost:6379,allowAdmin=true"; option.InstanceName = "foo-redis"; });
// add your classes to the `services` container services.AddSingleton<ICacheRepository, CacheRepository>();
var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName) .AddJsonFile("appsettings.json") .Build();
Read the values by name
1
var sdkKey = configuration["LaunchDarkly:SdkKey"];