I am struggling on what makes the ServiceLocator an anti-pattern.
Some say, that passing the container around qualifies it as an antipattern, others fear the maintainability once the app grows (hidden dependencies). The following sample demonstrates a simple registration with AutoFac including dependencies:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoFacSample
{
using System.Reflection;
using Autofac;
class Program
{
static void Main(string[] args)
{
var assembly = Assembly.GetExecutingAssembly();
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(assembly).Where(t => t.Name.Contains("First")).AsImplementedInterfaces();
Holder.Container = builder.Build();
var first = Holder.Container.Resolve<IFirst>();
}
}
public static class Holder
{
public static IContainer Container { get; set; }
}
public interface IFirst {}
public interface ISecond {}
public interface IThird {}
public class First : IFirst
{
public First(ISecond second)
{
}
}
public class Second : ISecond
{
public void Foo()
{
var third = Holder.Container.Resolve<IThird>();
}
}
public class Third : IThird {}
}
Would you consider my sample as an anti-pattern? If so, is there any good alternative?
EDIT:
I'm aware of the question Is ServiceLocator an anti-pattern? but the answer doesn't explain weather my sample is an anti-pattern or not.
Thanks,
Trini