Here is an example of a simple console application written in .NET that demonstrates the use of dependecy injection
It shows the use of the following services:
- IConfiguration from appsettings.json
- Console logging
Include the following packages from nuget:
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Json
- Microsoft.Extensions.Logging
- Microsoft.Extensions.Logging.Console
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Text;
namespace MyNamespace;
internal class Program
{
static ServiceProvider ConfigureServices()
{
ServiceCollection services = new ();
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", false)
.Build();
services.AddLogging(loggerBuilder =>
{
loggerBuilder.ClearProviders();
loggerBuilder.AddConsole();
});
services.AddSingleton<MyService>();
services.AddSingleton(configuration);
return services.BuildServiceProvider();
}
static async Task Main(string[] args)
{
ServiceProvider serviceProvider = ConfigureServices();
ICertificateManagerClient certificateManager = serviceProvider.GetRequiredService<MyService>();
IConfiguration configuration = serviceProvider.GetRequiredService<IConfiguration>();
string myValue = configuration.GetValue<string>("MyValue");
}
}