Created
November 2, 2016 00:26
-
-
Save greatb/1bfd9a5bd579a65e4eee1c4b074dacd0 to your computer and use it in GitHub Desktop.
C# Console app sample code for AutoFac DI and No-DI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!"); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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