C# – Unity Dependency Injection and Helper functions

cdependency-injection

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 same ISystemSettingService object as MyController. Passing it as a parameter like

 Validate(userData, _systemSettingService)

at all places where is Validateis called is surely a working approach. However, by making Validate 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 of Validate 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 same systemSettingService object provided to MyController. 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 class Validator, the same measures apply: passing the ISystemSettingService object directly to the method is not inherently wrong, but passing it to the constructor of Validator and making Validate non-static will probably result in more maintainable code.