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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With