Reputation: 2381
I just have started to design with DDD (I have no experience neither a teacher)
I have some domain service classes that have to reference each other in some point. So I decided to inject the references through constructor.
And when I created a view that has a lot of data to display in the controller I had to create a bunch of service (some of which referencing each other)
At this point one of my controller's first lines looked like this:
EmployeeRepository employRepository = new EmployeeRepository();
ShiftModelRepository shiftModelRepository = new ShiftModelRepository();
ShiftModelService shiftModelService = new ShiftModelService(shiftModelRepository);
EmployeeService employeeService = new EmployeeService(employRepository, shiftModelService);
OvertimeRepository overtimeRepository = new OvertimeRepository();
OvertimeService overtimeService = new OvertimeService(overtimeRepository, employeeService);
But I started to create interfaces for the services and using a IoC controller (named StructureMap)
And now the same controller's first lines looked like this:
IShiftModelService shiftModelService = ObjectFactory.GetInstance<IShiftModelService>();
IOvertimeService overtimeService = ObjectFactory.GetInstance<IOvertimeService>();
IEmployeeService employeeService = ObjectFactory.GetInstance<IEmployeeService>();
I think that it's far more good to use, but I to know if it is a good practice in DDD or not.
Upvotes: 5
Views: 1003
Reputation: 15767
Yes, it is OK to use an interface per implementation when you use DI (dependency injection) frameworks.
You should avoid ObjectFactory.GetInstance<IShiftModelService>()
and let your framework resolve dependencies automatically using YourImplementationOfControllerFactory
.
I haven't used Structure Map in my projects but I've been using Castle Windsor, another one dependency injection framework. Also you can have a look at Ninject.
Anyway, there are steps that are similar for many frameworks:
DefaultControllerFactory
. Global.asax.cs
.Global.asax.cs
.Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
/* code that bootstraps your container */
//Set the controller builder to use our custom controller factory
var controllerFactory = new YourControllerFactory();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
}
}
There are several useful links:
Upvotes: 2
Reputation: 6786
Using interfaces is almost always preferable and good practice - so what you have in the second example is better.
But as StuartLC mentions, your really want to look at injecting these dependencies as constructor arguments.
ObjectFactory.GetInstance is really a kind of service locator which is generally not the best pattern to use as the object doesn't declare what dependencies it has. It is generally better to expose the dependencies as constructor arguments and have them injected in.
Upvotes: 2