Skip to content

Instantly share code, notes, and snippets.

@nycdotnet
Created April 30, 2019 20:47
Show Gist options
  • Save nycdotnet/6428d8757967b900ac33ee2d8b734c68 to your computer and use it in GitHub Desktop.
Save nycdotnet/6428d8757967b900ac33ee2d8b734c68 to your computer and use it in GitHub Desktop.
Autofac Demo
using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
// You must add the `Autofac` and `Microsoft.Extensions.Configuration` NuGet packages for this to work
namespace AutofacDemo
{
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Greeter>();
builder.Register(c => {
var config = new MyConfig();
config.Data["greeting"] = "Greg @ " + DateTime.Now.ToString();
return config;
}).As<IConfiguration>();
var container = builder.Build();
var greeter = container.Resolve<Greeter>();
greeter.Greet();
Thread.Sleep(3000);
greeter.Greet();
Console.ReadKey();
}
}
public class Greeter
{
private readonly IConfiguration config;
public Greeter(IConfiguration config)
{
this.config = config;
}
public void Greet()
{
Console.WriteLine($"Hello {config["greeting"]}");
}
}
public class MyConfig : IConfiguration
{
public Dictionary<string, string> Data = new Dictionary<string, string>();
public string this[string key] { get => Data[key]; set => Data[key] = value; }
public IEnumerable<IConfigurationSection> GetChildren()
{
throw new NotImplementedException();
}
public IChangeToken GetReloadToken()
{
throw new NotImplementedException();
}
public IConfigurationSection GetSection(string key)
{
throw new NotImplementedException();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment