Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Autofac IComponentContext.Resolve<Type> a service locator pattern

In a recent code review, I found the class resolver by IComponentContext as shown in below example:

using Autofac;

public class BaseClass
{
    protected IComponentContext _componentContext;
    public BaseClass(IComponentContext componentContext)
    {
        _componentContext = componentContext;
    }
}

public class MyClass1: BaseClass
{
   protected IMyClass2 _myClass2 = _componentContext.Resolve<MyClass2>();
   public void Operation1()
   {
        _myClass2.Operation2();
   }
}

I feel the above code is resolving MyClass2 outside of Class1() constructor. Isn't it a service locator pattern and voilating IOC?

like image 410
gee'K'iran Avatar asked Mar 05 '23 22:03

gee'K'iran


1 Answers

Yes, this is an example of using the service locator pattern. To fix it, your BaseClass should take no IComponentContext (to ensure no other service location happens) and the MyClass1 should take a constructor parameter of type IMyClass2.

like image 104
Travis Illig Avatar answered Mar 11 '23 02:03

Travis Illig