Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.