I have a set of services that are used to read/write to the database. These get injected into my controllers:
ISystemSettingService _systemSettingService = null;
IStatusTypeService _statusTypeservice = null;
public MyController(
ISystemSettingService systemSettingService,
IStatusTypeService statusTypeservice)
{
_systemSettingService = systemSettingService;
_statusTypeservice = statusTypeservice;
}
So when I need something from _systemSettingService
I can easily get it. Now I also have some static helper classes/functions which I call from MyController
. In these functions I often need access to the services so I can access the DB. e.g. I have a Validate(string userData, ISystemSettingService systemSettingService)
function that accepts some data passed in from the user.
So far, into the Validate
function I have been passing in the _systemSettingService
so I can use it. I'm not sure this is correct.
My question – is my approach correct or, in the Validate
function should I be creating a unity container to Resolve
an instance of my ISystemSettingService
or, as I have been reading about, should my helper class NOT be static, and I should inject ISystemSettingService
into the constructor which will apparently make unit testing easier.
I'm a bit confused! Thanks.
Best Answer
Your questions sounds a little bit confused about
Validate
being a function or a class, but for sake of simplicity, let us assume it is a function.If I got you right, you want to make sure your
Validate
function uses internally the sameISystemSettingService
object asMyController
. Passing it as a parameter likeat all places where is
Validate
is called is surely a working approach. However, by makingValidate
non-static, you can actually reach the same goal in a more readable and less error-prone fashion. So if all calls to the static version ofValidate
would use_systemSettingService
as a second parameter, with no exceptions, then making it non-static and saving the second parameter is IMHO the better alternative.Usage of a DI container for the helper function will probably make the code longer, less readable, more complex and error prone, since you have to make sure the
Resolve
method will return the samesystemSettingService
object provided toMyController
. IMHO it is better to use a DI container exclusively where it clearly makes things simpler.In case
Validate
is a method of a helper classValidator
, the same measures apply: passing theISystemSettingService
object directly to the method is not inherently wrong, but passing it to the constructor ofValidator
and makingValidate
non-static will probably result in more maintainable code.