I have a OrderService that I use in my controllers.
What I did was just inherit from a custom controller where I added the OrderService as a property. I initialize the OrderService in the OnActionExecuting event.
When initializing the OrderService, I set the Order property.
This is because the OrderService performs actions on a Order, so it makes sense to set it once instead of having to pass in a Order into every method.
Is this design following good practices?
public class MyController : Controller
{
public OrderService OrderService {get; set;}
protected override void OnActionExecuting(...)
{
OrderService = new OrderService(getOrderIdFromCookie());
}
}
public class OrderService
{
private Order _order;
public OrderService(int orderId)
{
_order = Dao.GetOrderById(orderId);
}
public void AddProduct(Product product)
{
product.OrderId = _order.Id; // assumes order is loaded
ProductDao.Add(product);
}
}
This is really a language independent question, from what I understand, a service should not really hold any state of any kind.
I believe a Service layer class should be a singleton correct? (when setting it up with dependancy injection).
The methods shouldn't assume that the Order object has state.
If that is the case, then my design is not correct right?