I would like to use Autofac in console application. It is my really first usage. Before that I was using it in ASP.NET MVC only. In MVC project I can setup Autofac in Global.asax, inject IService to controller and we can say more and less it works. In console application I do it like below:
internal class Program
{
private static IContainer Container { get; set;}
private static void Main(string[] args)
{
Container = Container.Configure(); // here I have all necessary objects set
// now I can use it in Main method as:
using (var scope = Container.BeginLifetimeScope())
{
scope.Resolve<ISomething>();
}
}
}
As you can see usage of it is simple in just Main method. How about using it in external class? Let say I would like to create class Cat, and inside that use Autofac. should I pass to contructor object Container from class Program? E.g.:
Cat cat = new Cat(Program.Container, "Molly");
Or maybe I should create IContainer inside Cat class?
What is the best solution?
Only your console application really needs to know about AutoFac, otherwise you're falling onto the service locator pattern, which is often considered an anti-pattern. Instead, your application should follow this pattern:
//in your console application
using (var scope = Container.BeginLifetimeScope())
{
IServiceservice = scope.Resolve<IService>();
service.Execute();
}
class SomeService : IService
{
readonly ISomeDependency _dependency;
public SomeService(ISomeDependency dependency)
{
_dependency = dependency;
}
public void Execute()
{
_dependency.DoSomething();
}
}
interface IService
{
void Execute();
}
Notice I never actually call a constructor. I make it a habit to never "new up" an object unless that object is just a POCO (contains only data, no logic).
Note that ISomeDependency
can itself depends on 0 or more other classes, which it takes via constructor injection. Since AutoFac created the IService
, and all of its dependencies, including ISomeDependency
, all of ISomeDependency
's dependencies will also be initialized, and so forth all the way down. A good video demonstrating this concept is Miguel Castro's Deep Dive into Dependency Injection and Writing Decoupled Quality Code and Testable Software.