I'm trying to create an generic service-interface per logic-class to communicate with the database. See code examples for an explanation better than words.
For example:
Foo
public interface ICreateFoo
{
void CreateFoo(Foo foo);
}
public interface IReadFoo
{
void ReadFoo(Foo foo);
}
Bar
public interface ICreateBar
{
void CreateBar(Bar bar);
}
public interface IReadBar
{
void ReadBar(Bar bar);
}
IFooService
public interface IFooService : ICreateFoo, IReadFoo, IReadBar
{ }
FooService instance
public class FooService : ICreateFoo, IReadFoo
{
public void CreateFoo(Foo foo){
//Something
}
public void ReadFoo(Foo foo){
//Something
}
}
BarService instance
public class BarService : ICreateBar, IReadBar
{
public void CreateBar(Bar bar){
//Something
}
public void ReadBar(Bar bar){
//Something
}
}
FooLogic instance
public class FooLogic : IFooService
{
private readonly IFooService _fooService;
public FooLogic(IFooService fooService) {
_fooService = fooService;
}
public void CreateFoo(Foo foo){
//Check if bar exists
if(_fooService.ReadBar())
_fooService.AddFoo(foo);
else
//nothing
}
}
But the dependency injection ofcourse doesn't know which service
class instance it should get, is this a bad usage of interfaces? Because it looks clean to me, but I don't know how to implement yet.
The reason I came up with this is because I need to know if Bar exists or not before adding Foo to the database. I wanted the classes according to the SOLID-principles (each class has it's own responsibilities). Or is it better to inject each service in the Logic so, like this:
public class FooLogic
{
private readonly IFooService _fooService;
private readonly IBarService _barService;
public FooLogic(IFooService fooService, IBarService barService) {
_fooService = fooService;
_barService = barService;
}
public void CreateFoo(Foo foo){
//Check if bar exists
if(_barService.ReadBar())
_fooService.AddFoo(foo);
else
//nothing
}
}
Maybe you have a complete different but better approach, let me know! I appreciate code examples :)
Keep it simple! Create FooService that implements IFooService. FooLogic should be removed. You can implement the logic inside the method CreateFoo.
Since FooService will impement all the methods, you can call ReadBar() instead of _barService.ReadBar(), there is no need for composition since you already have IFooService inheriting from all other interfaces.
This way, we are still respecting the dependency injection pattern.