Skip to content

Instantly share code, notes, and snippets.

@CuddleBunny
Last active December 1, 2019 11:16
Show Gist options
  • Save CuddleBunny/9805d2042b0dfa620630fa38724895d0 to your computer and use it in GitHub Desktop.
Save CuddleBunny/9805d2042b0dfa620630fa38724895d0 to your computer and use it in GitHub Desktop.
DotNetCore Console App with DI and ConfigurationBuilder
{
"test": "Hello from Core DI"
}
using Microsoft.Extensions.Configuration;
using System;
namespace CoreConsole {
public interface ICustomService {
}
public class CustomService : ICustomService {
public CustomService(IConfigurationRoot config) {
Console.WriteLine(config["test"]);
}
}
}
using System;
using Microsoft.Extensions.DependencyInjection;
namespace CoreConsole {
public class Program {
public static void Main(string[] args) {
IServiceCollection services = new ServiceCollection();
Startup startup = new Startup();
startup.ConfigureServices(services);
IServiceProvider provider = services.BuildServiceProvider();
// Test grabbing a service
provider.GetRequiredService<ICustomService>();
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true,
"copyToOutput": {
"include": "appsettings.json"
}
},
"dependencies": {
"Microsoft.Extensions.Configuration": "1.0.0",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.DependencyInjection": "1.0.0",
"Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CoreConsole {
public class Startup {
IConfigurationRoot configuration { get; }
public Startup() {
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton<IConfigurationRoot>(configuration);
services.AddSingleton<ICustomService, CustomService>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment