Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good design practice to have an interface for each service class in DDD?

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.

like image 289
jannagy02 Avatar asked Oct 03 '22 16:10

jannagy02


1 Answers

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.

like image 180
Matt Whetton Avatar answered Oct 13 '22 12:10

Matt Whetton