This example will show how get started with Inverion of Control using Autofac with a relatively simple project, closely following the official getting started docs.
Create a console application from File -> New -> Project -> Console Application
Install Autofac for this project. You can take a look here Installing Autofac
Add 2 interfaces and 2 classes, with the following names:
Interfaces | Classes
--------------------------
IOutput | ConsoleOutput (implementing IOutput)
IDateWriter | TodayWriter (implementing IDateWriter)
For simplicity, the using statements and namespaces are not shown.
public interface IOutput
{
void Write(string content);
}
public class ConsoleOutput : IOutput
{
public void Write(string content)
{
Console.WriteLine(content);
}
}
public interface IDateWriter
{
void WriteDate();
}
public class TodayWriter : IDateWriter
{
private IOutput _output;
public TodayWriter(IOutput output)
{
_output = output;
}
public void WriteDate()
{
_output.Write(DateTime.Today.ToShortDateString());
}
}
So far the code has been plain and simple. Lets get to the part where automatic dependency injection takes place, which of course is being done by Autofac!
Replace the Program
class in Program.cs file with this code (Program
class is automatically created by Visual Studio at project creation. If it doesn't exist, go ahead and create one):
class Program
{
private static IContainer Container { get; set; }
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<ConsoleOutput>().As<IOutput>();
builder.RegisterType<TodayWriter>().As<IDateWriter>();
Container = builder.Build();
WriteDate();
}
public static void WriteDate()
{
using (var scope = Container.BeginLifetimeScope())
{
var writer = scope.Resolve<IDateWriter>();
writer.WriteDate();
}
}
}
When run, the output should be the current date in the console. You have successfully used Autofac in your project to inject dependencies automatically.
Here is what's going on under the hood:
At application startup, we are creating a ContainerBuilder
and registering our Components with it. A component in simple terms is a .NET type that implements an interface, and thus exposes some services. Read Services vs. Components.
We then register our components (classes) with the services (interfaces) they expose. When registered, Autofac knows which instance of a class to create when an interface is to be resolved.
Finally, when we run the program:
WriteDate()
method (in Main()
) asks Autofac for an IDateWriter
.IDateWriter
maps to TodayWriter
so starts creating a TodayWriter
.TodayWriter
needs an IOutput
in its constructor.IOutput
maps to ConsoleOutput
so creates a new ConsoleOutput
instance.ConsoleOutput
instance to finish constructing the TodayWriter
.TodayWriter
for WriteDate()
to consume.