Skip to content

Instantly share code, notes, and snippets.

@greatb
Created November 2, 2016 00:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save greatb/1bfd9a5bd579a65e4eee1c4b074dacd0 to your computer and use it in GitHub Desktop.
Save greatb/1bfd9a5bd579a65e4eee1c4b074dacd0 to your computer and use it in GitHub Desktop.
C# Console app sample code for AutoFac DI and No-DI
using Autofac;
using System;
namespace AutoFacHW
{
class Program
{
static void Main(string[] args)
{
var container = ContainerConfig.Configure();
using (var scope = container.BeginLifetimeScope())
{
var app = scope.Resolve<IApplication>();
app.Run();
}
}
}
public interface IApplication
{
void Run();
}
public interface IService
{
void WriteInformation(string message);
}
public class Service : IService
{
public void WriteInformation(string message)
{
Console.WriteLine(message);
}
}
public static class ContainerConfig
{
public static IContainer Configure()
{
var builder = new ContainerBuilder();
builder.RegisterType<Application>().As<IApplication>();
builder.RegisterType<Service>().As<IService>();
return builder.Build();
}
}
public class Application : IApplication
{
private readonly IService _service;
public Application(IService service)
{
_service = service;
}
public void Run()
{
_service.WriteInformation("Injected!");
}
}
}
using System;
namespace NoDI
{
class Program
{
static void Main(string[] args)
{
var app = new Application();
app.Run();
}
}
public interface IService
{
void WriteInformation(string message);
}
public class Service : IService
{
public void WriteInformation(string message)
{
Console.WriteLine(message);
}
}
public class Application
{
private readonly IService _service;
public Application()
{
_service = new Service();
}
public void Run()
{
_service.WriteInformation("No DI!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment