I am currently learning dependency injection to create more maintainable code with MVC. I am already injecting a model and a calculator service to my controller instead of having a to new up dependency.
I have a few Convert.ToDecimal calls in my constructor, and didn't know if I needed to worry about using dependency injection to remove the static method call which is a DI design smell. Is removing that going too far?
private readonly ICalculationService _calculation;
private readonly ICalculatorModelService _calculatormodel;
public CalculatorController(ICalculationService calculation,
ICalculatorModelService calculatormodel) {
_calculation = calculation;
_calculatormodel = calculatormodel;
}
public ActionResult Index() {
var model = _calculatormodel;
return View(model);
}
public PartialViewResult Calculate(string submit, string txtValue,
string value1) {
var model = _calculatormodel;
if (submit == "+")
{
if (Session["value1"] == null)
Session.Add("value1",Convert.ToDecimal(txtValue));
else
Session["value1"] = value1;
}
else if (submit == "=")
{
if (Session["value1"] == null)
Session.Add("value1", 0);
model.Result = _calculation.Calculate(Convert
.ToDecimal(Session["value1"]), Convert.ToDecimal(txtValue));
}
return PartialView("_Calculator", model);
}
If I understand the question, you are worried about the static call of Convert
and you ask if this class should also be injected.
If that's the case, you don't have too. Same goes for similar static calls like Math.
methods etc.
The rule I follow for such .NET helper calls is, if the call is deterministic, i.e. always returning same output for the same input, then go ahead call it (anyway you depend on .NET framework, right?). But if the call is non deterministic, like Datetime.Now
or use of Random
class, then I inject these dependencies (which makes code more testable, of course)