Introduction
I’m using ASP.Net MVC3. My Controllers talk to a service layer, and the service layer talks to a Data Acces layer which uses Entity Framework.
I get a specific entity using Entity Framework. This entity is converted into a DTO. Then I deliver this DTO to a MVC controller. Something like this:
pseudo code:
// This is inside my Service Layer
var entity = DataAccess.GetById(id);
var dto = createDtoWithValuesFrom(entity);
return dto; // Return dto to MVC controller
In this DTO I would like to use a dependency, to for example a Calculator. Let’s say my DTO looks like this:
public class Customer
{
private ICalculator Calculator;
public class Customer(ICalculator calculator)
{
Calculator = calculator;
}
public string Name { get; set; }
public decimal Discount
{
get
{
return Calculator.Discount();
}
}
}
Problem
How do I instanciate my DTO, and let Autofac inject a calculator?
I can think of a way to do this:
var calculator = DependencyResolver.Current.GetService<ICalculator>;
var dto = new DTO(calculator );
But I don’t know if this is the best way to do it, since it smells of ServiceLocator, and I’ve read that it’s not prefered to use that.
DTOs normally have some properties and do not contain any logic.
You should consider a design where your MVC-Controller does something like this:
public class Model { public Customer Customer { get; set; } public double Discount { get; set; } } public class SomeController : Controller { private readonly DataAccess dataAccess; private readonly ICalculator calculator; public SomeController(DataAccess dataAccess, ICalculator calculator) { this.dataAccess = dataAccess; this.calculator = calculator; } public ActionResult Index(int id) { var model = new Model(); model.Customer = this.dataAccess.Get(id); model.Discount = this.calculator.Calculate(customer); return View(model); } }