Should service layer accept a DTO or a custom request object from the controller? - rest

As the title suggests what is the best practice when designing service layers?. I do understand service layer should always return a DTO so that domain (entity) objects are preserved within the service layer. But what should be the input for the service layer from the controllers?
I put forward three of my own suggestions below:
Method 1:
In this method the domain object (Item) is preserved within the service layer.
class Controller
{
#Autowired
private ItemService service;
public ItemDTO createItem(IntemDTO dto)
{
// service layer returns a DTO object and accepts a DTO object
return service.createItem(dto);
}
}
Method 2:
This is where the service layer receives a custom request object. I have seen this pattern extensively in AWS Java SDK and also Google Cloud Java API
class Controller
{
#Autowired
private ItemService service;
public ItemDTO createItem(CreateItemRequest request)
{
// service layer returns a DTO object and accepts a custom request object
return service.createItem(request);
}
}
Method 3:
Service layer accepts a DTO and returns a domain object. I am not a fan of this method. But its been used extensively used at my workplace.
class Controller
{
#Autowired
private ItemService service;
public ItemDTO createItem(CreateItemRequest request)
{
// service layer returns a DTO object and accepts a DTO object
Item item = service.createItem(request);
return ItemDTO.fromEntity(item);
}
}
If all 3 of the above methods are incorrect or not the best way to do it, please advise me on the best practice.

Conceptually speaking, you want to be able to reuse the service/application layer across presentation layers and through different access ports (e.g. console app talking to your app through a web socket). Furthermore, you do not want every single domain change to bubble up into the layers above the application layer.
The controller conceptually belongs to the presentation layer. Therefore, you wouldn't want the application layer to be coupled upon a contract defined in the same conceptual layer the controller is defined in. You also wouldn't want the controller to depend upon the domain or it may have to change when the domain changes.
You want a solution where the application layer method contracts (parameters & return type) are expressed in any Java native types or types defined in the service layer boundary.
If we take an IDDD sample from Vaughn Vernon, we can see that his application service method contracts are defined in Java native types. His application service command methods also do not yield any result given he used CQRS, but we can see query methods do return a DTO defined in the application/service layer package.
In the above listed 3 methods which ones are correct/wrong?
Both, #1 and #2 are very similar and could be right from a dependency standpoint, as long as ItemDto and CreateItemRequest are defined in the application layer package, but I would favor #2 since the input data type is named against the use case rather than simply the kind of entity it deals with: entity-naming-focus would fit better with CRUD and because of that you might find it difficult to find good names for input data types of other use case methods operating on the same kind of entity. #2 also have been popularized through CQRS (where commands are usually sent to a command bus), but is not exclusive to CQRS. Vaughn Vernon also uses this approach in the IDDD samples. Please note that what you call request is usually called command.
However, #3 would not be ideal given it couples the controller (presentation layer) with the domain.
For example, some methods receive 4 or 5 args. According to Eric Evans in Clean Code, such methods must be avoided.
That's a good guideline to follow and I'm not saying the samples couldn't be improved, but keep in mind that in DDD, the focus is put on naming things according to the Ubiquitous Language (UL) and following it as closely as possible. Therefore, forcing new concepts into the design just for the sake of grouping arguments together could potentially be harmful. Ironically, the process of attempting to do so may still offer some good insights and allow to discover overlooked & useful domain concepts that could enrich the UL.
PS: Robert C. Martin has written Clean Code, not Eric Evans which is famous for the blue book.

I'm from C# background but the concept remains same here.
In a situation like this, where we have to pass the parameters/state from application layer to service layer and, then return result from service layer, I would tend to follow separation-of-concerns. The service layer does not need to know about the Request parameter of you application layer/ controller. Similarly, what you return from service layer should not be coupled with what you return from your controller. These are different layers, different requirements, separate concerns. We should avoid tight coupling.
For the above example, I would do something like this:
class Controller
{
#Autowired
private ItemService service;
public ItemResponse createItem(CreateItemRequest request)
{
var creatItemDto = GetDTo(request);
var itemDto = service.createItem(createItemDto);
return GetItemResponse(itemDto);
}
}
This may feel like more work since now you need to write addional code to convert the different objects. However, this gives you a great flexiblity and makes the code much easier to maintain. For example: CreateItemDto may have additional/ computational fields as compared to CreateItemRequest. In such cases, you do not need to expose those fields in your Request object. You only expose your Data Contract to the client and nothing more. Similarly, you only return the relevant fields to the client as against what you return from service layer.
If you want to avoid manual mapping between Dto and Request objects C# has libaries like AutoMapper. In java world, I'm sure there should be an equivalent. May be ModelMapper can help.

Related

Entity Framework & WPF Application Design Guidance

Entity Framework Layer Guidance
I'm in the design stage of a WPF business application. The first stage of this application will be a WPF/Desktop application. Later iterations may include a browser based mini version.
I envision creating a dll or 2 that contain the domain model & dbcontext that all applications(Desktop or Browser) will use.
My intention is to ride or die with EF. I'm not worried about using DI/Repository patterns etc for flexibility. The benefits of using them don't outweigh the added complexity in my opinion for this project. My plan is to use a model, and a derived dbcontext.
Having said that, I'm looking for input on where to put certain types of method code.
An example will hopefully make my question more clear:
Let's say I have the following two entities..
Entity: Employee
Entity: PermissionToken
Inside of these two entities I have a ManyToMany relationship resulting in me creating another entity for the relationship:
EmployeesPermissionTokens
For clarity, the PermissionToken Entity's Primary Key is an Enum representing the permission..
In the application, lets say the current user is Administering Employees and wants to grant a permission to an Employee.
In the app, I could certainly code this as:
var e = dbcontext.Employees.Find(1);
var pt = new PermissionToken
{
PermissionID=PermissionTypeEnum.DELETEUSER";
...
}
e.PermissionTokens.Add(pt)
But it seems to me that it would be more convenient to wrap that code in a method so that one line of code could perform those actions from whatever application chooses to do so. Where would a method like that live in all of this?
I've thought about adding a static method to the EF Entity:
In The employee class:
public static void GrantPermission(PermissionToken token)
{
e.PermissionTokens.Add(token);
}
Going further, what would be really convenient for the app would be the ability to write a line like this:
Permissions.GrantToEmployee(EmployeeID employeeId, PermissionTypeEnum
permissionId);
Of course that means that the method would have to be able to access the DbContext to grab the Employee Object and the PermissionObject by ID to do its work. I really want to avoid my entities knowing about/calling DbContext because I feel long term the entities get stuffed full of dbcontext code which in my opinion shouldn't even be in the Model classes.
So Where would a method like this go?
My gut tells me to put these sorts of code in my derived DbContext since in order to do these sorts of things, the method is going to need access to a DbContext anyway.
Does this make sense, or am I missing something? I hate to write oodles of code and then figure out 3 months later that I went down the wrong road to start with. Where should these types of methods live? I know there is probably a purist answer to this, but I'm looking for a clean, real world solution.
First of all you are making a good decision to not abstract EF behind a repository.
With the EF Context you have a class supporting the Unit Of Work pattern which is handling your data access needs.No need to wrap it up in repository.
However this does not mean you should call the Context directly from your controller or viewmodel.
You could indeed just extend the DbContext however I suggest to use services to mediate between your controllers/view models and your dbcontext.
If e.g. in your controller you are handling a user request (e.g. the user has clicked a button) then your controller should call a service to archive what ever "Use Case" is behind the button.
In your case this could be a PermissionService, the PermissionService would be the storage for all operations concerning permission.
public class PermissionService
{
PermissionService(DbContext context)
{
}
public bool AddPermission(Employee e, PermissionType type) { }
public bool RemovePermission(Employee e, PermissionType type) {}
}
Your service ofcourse needs access to the DbContext.
It makes sense to use DI here and register the DbContext with a DI Container.
Thus the context will be injected into all your services. This is pretty straight forward and I do not see any extra complexity here.
However, if you don't want to do this you can simply new up up the Db Context inside your services. Of course this is harder / impossible to mock for testing.

How correctly implement a RESTful WS architecture using Spring MVC\Boot?

I am not so into RESTful web service and I have the following doubt about how to correctly implement RESTful style in my servics working on a Spring Boot application (Spring MVC is the same thing).
So basically I have some controller class like this:
#RestController
#RequestMapping("/RoomMedia")
public class RoomMediaController {
private static final Logger log = LoggerFactory.getLogger(RoomMediaController.class);
#Autowired
private RoomMediaService roomMediaService;
public RoomMediaController() {
log.debug("RoomMediaController init");
}
#RequestMapping(value = "getAllImagesByRoomId",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<byte[]>> getAllImagesByRoomId(Long roomId) throws DataAccessException {
log.debug("getAllImagesByRoomId START");
List<byte[]> result = roomMediaService.getRoomImageListById(roomId);
log.debug(result.toString());
log.debug("getAllImagesByRoomId END");
return ResponseEntity.ok(result);
}
}
I think that, also if the base idea is RESTful like, it can't be considered a true RESTful WS.
I think that the main problem is related to the endpoint: the getAllImagesByRoomId() method handle HTTP GET request toward URL like this: /RoomMedia/getAllImagesByRoomId?roomId=7
From what I have understand reading some tutorial this is not RESTful style because I have to access to a resource without passing parameter, I have to do someting like this:
/RoomMedia/Images/7
Is it my reasoning correct?
Moreover I think that the previous method is pretty trivial also in the implementation: this method return the list of all the images associated to a room having id=7(it is an application related to hotels).
From what I have understand also its logic is againts RESTful principles.
Is it better organize in the following way?
Doing a GET request like this:
/RoomMedia/7/Images/: I have to obtain the list of all the images associated to the room having id=7 as URI (or maybe is better handle a path like /7/RoomMedia/Images/ ?).
/RoomMedia/7/Images/1 I obtain the image with the id=1 associated to the room having id=7.
Are al these reasoning correct or am I missing something?
your assumtions are correct. Which of the mapping that you suggest, is deppending totaly on how your model is. Martin Fowler has a nice article about the Richardson Maturity Model which is sum up as:
Level 1 tackles the question of handling complexity by using divide and conquer, breaking a large service endpoint down into multiple resources.
Level 2 introduces a standard set of verbs so that we handle similar situations in the same way, removing unnecessary variation.
Level 3 introduces discoverability, providing a way of making a protocol more self-documenting.
For your project you could use jhipster because its offer you the best of spring with angular under a REST-ful design.
URLs must not contain a verb. The verb is provided by the method, in your case - surprise, surprise - GET.
ByRoomId is pointless as well, because that's what ?roomId= says.
That leaves AllImages, where All is superfluous.
Which results in the URL /RoomMedia/Images?roomId=7. What's unclear is the relationship between RoomMedia and Images, if there is any. If RoomMedia refers to a room, then your suggestion /RoomMedia/7/Images/ would be correct.
/RoomMedia/7/Images/1 is questionable. It should rather be /Images/1. It's irrelevant in which room the image with the id 1 is in.
When you design a REST API, then the first thing to do is to think about all resources you want to expose and their relationships. After that the URLs will reveal themselves automatically, so to speak.

Implementing Bounded Context with Entity Framework in a 3-Layer Architecture

I have watched Julie Lerman's videos about using EF in an enterprise application. Now I am developing a website using "Bounded Contexts" and other stuff she has taught in that series.
The problem is I do not know how to use bounded contexts (BC) from within my "Business Layer". To make it clearer: How should the BL know that which specific BC it should use.
Suppose the UI requests a list of products from the business layer. In BL I have a method that returns a list of products: GetAll(). This method does not know which part of the UI (site admin, moderator or public user) has requested the list of products. Since each user/scenario has its own bounded context, the list needs to be pulled using that related context. How should the BL choose the appropriate BC?
Moreover I do not want the UI layer to interact with data layer.
How can this be done?
If by business layer you mean a place where all your business rules are defined, then that is a bounded context.
A bounded context looks at your system from a certain angle so that business rules can be implemented in a compartmentalised fashion (with the goal that it is easier to handle the overall problem by splitting in to smaller chunks).
http://martinfowler.com/bliki/BoundedContext.html
Front-end
So assuming you have a ASP MVC front end, this controllers are the things that will call your use cases/user stories that are presented from the domain to be called via a standard known interface.
public class UserController : Controller
{
ICommandHandler<ChangeNameCommand> handler;
public UserController(ICommandHandler<ChangeNameCommand> handler)
{
this.handler = handler;
}
public ActionResult ChangeUserName(string id, string name)
{
try
{
var command = new ChangeNameCommand(id,name);
var data = handler.handle(command);
}
catch(Exception e)
{
// add error logging and display info
ViewBag.Error = e.Message;
}
// everything went OK, let the user know
return View("Index");
}
}
Domain Application (Use Cases)
Next, you would have an domain application entry point that implements the use case (this would be a command or query handler).
You may call this directly and have the code run in-process with your front end application, or you may have a WebAPI or WCF service in front of it presenting the domain application services. It doesn't really matter, how you the system is distrusted depends on the system requirements (it is often simpler from an infrastructure perspective to not to distribute if not needed).
The domain application layer then orchestrates the user story - it will new up repositories, fetch entities, perform an operation on them, and then write back to the repository. The code here should not be complex or contain logic.
public class NewUserHandler : ICommandHandler<ChangeNameCommand>
{
private readonly IRepository repository;
public NewUserHandler(IRepository repository)
{
this.repository = repository;
}
public void Handle(ChangeUserName command)
{
var userId = new UserId(command.UserId);
var user = this.repository.GetById<User>(userId);
user.ChangeName(command.NewName);
this.repository.Save(newUser);
}
}
Domain Model
The entities them selves implement their own business logic in the domain model. You may also have domain services for logic which doesn't naturally fit nicely inside an individual entity.
public class User
{
protected string Name;
protected DateTime NameLastChangedOn;
public ChangeName(string newName)
{
// not the best of business rules, just an example...
if((DateTime.UtcNow - NameLastChangedOn).Days < 30)
{
throw new DomainException("Cannot change name more than once every 30 days");
}
this.Name = newName;
this.NameLastChangedOn = DateTime.UtcNow;
}
}
Infrastructure
You would have infrastructure which implements the code to fetch and retrieve entities from your backing store. For you this is Entity Framework and the DbContext (my example code above is not using EF but you can substitute).
Answer to your question - Which bounded context should the front end application call?
Not to make the answer complex or long, but I included the above code to set the background and hope to make it easier to understand as I think the terms you are using are getting a little mixed up.
With the above code as you started implementing more command and query handlers, which bounded context is called from your front end application depends on what specific user story the user wishes to perform.
User stories will generally be clustered across different bounded contexts, so you would just select the command or query for the bounded context that implements the required functionality - don't worry about making it anything more complicated than that.
Let the problem you are trying to solve dictate the mapping, and dont be afraid that this mapping will possibly change as insight in to the problem you are looking to solve improves.
Sidenote
As a side note to mention things I found useful (I started my DDD journey with EF)... with entity framework there are ORM concepts that are often required such as defining mapping relationships and navigation properties between entities, and what happens with cascade deletes and updates. For me, this started to influence how I designed my entities, rather than the problem dictating how the entities should be designed. You may find this interesting: http://mehdi.me/ambient-dbcontext-in-ef6/
You may also want to look at http://geteventstore.com and event sourcing which takes away any headaches of ORM mapping (but comes with added complexity and workarounds needed to get acceptable performance). What is best to use depends on the situation, but its always good to know all the options.
I also use SimpleInjector to wire up my classes and inject in to the MVC controller (as a prebuilt Command or Query handler), more info here: https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91.
Using an IoC container is a personal preference only and not set in stone.
This book is also awesome: https://vaughnvernon.co/?page_id=168
I mention the above as I started my DDD journey with EF and the exact same question you had.

ViewModel -> Model: Who's responsible for persistance logic?

in my ASP MVC 2 application I follow the strongly typed view pattern with specific viewmodels.
Im my application viewmodels are responsible for converting between models and viewmodels. My viewmodels I have a static ToViewModel(...) function which creates a new viewmodel for the corresponding model. So far I'm fine with that.
When want I edit a model, I send the created viewmodel over the wire and apply the changes to back to the model. For this purpose I use a static ToModel(...) method (also declared in the view model). Here the stubs for clarification:
public class UserViewModel
{
...
public static void ToViewModel(User user, UserViewModel userViewModel)
{
...
}
public static void toModel(User user, UserViewModel userViewModel)
{
???
}
}
So, now my "Problem":
Some models are complex (more than just strings, ints,...). So persistence logic has to be put somewhere.(With persistence logic I mean the decisions wheater to create a new DB entry or not,... not just rough CRUD - I use repositories for that)
I don't think it's a good idea to put it in my repositories, as repositories (in my understanding) should not be concerned with something that comes from the view.I thought about putting it in the ToModel(...) method but I'm not sure if thats the right approach.
Can you give me a hint?
Lg
warappa
Warappa - we use both a repository pattern and viewmodels as well.
However, we have two additonal layers:
service
task
The service layer deals with stuff like persisting relational data (complex object models) etc. The task layer deals with fancy linq correlations of the data and any extra manipulation that's required in order to present the correct data to the viewmodel.
Outwith the scope of this, we also have a 'filters' class per entity. This allows us to target extension methods per class where required.
simples... :)
In our MVC projects we have a seperate location for Converters.
We have two types of converter, an IConverter and an ITwoWayConverter (a bit more too it than that but I'm keeping it simple).
The ITwoWayConverter contains two primary methods ConvertTo and ConvertFrom which contain the logic for converting a model to a view model and visa versa.
This way you can create specific converts for switching between types such as:
public class ProductToProductViewModelConverter : ITwoWayConverter<Product,ProductViewModel>
We then inject the relevant converters into our controller as needed.
This means that your conversion from one type to another is not limited by a single converter (stored inside the model or wherever).

ServiceContainer, IoC, and disposable objects

I have a question, and I'm going to tag this subjective since that's what I think it evolves into, more of a discussion. I'm hoping for some good ideas or some thought-provokers. I apologize for the long-winded question but you need to know the context.
The question is basically:
How do you deal with concrete types in relation to IoC containers? Specifically, who is responsible for disposing them, if they require disposal, and how does that knowledge get propagated out to the calling code?
Do you require them to be IDisposable? If not, is that code future-proof, or is the rule that you cannot use disposable objects? If you enforce IDisposable-requirements on interfaces and concrete types to be future-proof, whose responsibility is objects injected as part of constructor calls?
Edit: I accepted the answer by #Chris Ballard since it's the closest one to the approach we ended up with.
Basically, we always return a type that looks like this:
public interface IService<T> : IDisposable
where T: class
{
T Instance { get; }
Boolean Success { get; }
String FailureMessage { get; } // in case Success=false
}
We then return an object implementing this interface back from both .Resolve and .TryResolve, so that what we get in the calling code is always the same type.
Now, the object implementing this interface, IService<T> is IDisposable, and should always be disposed of. It's not up to the programmer that resolves a service to decide whether the IService<T> object should be disposed or not.
However, and this is the crucial part, whether the service instance should be disposed or not, that knowledge is baked into the object implementing IService<T>, so if it's a factory-scoped service (ie. each call to Resolve ends up with a new service instance), then the service instance will be disposed when the IService<T> object is disposed.
This also made it possible to support other special scopes, like pooling. We can now say that we want minimum 2 service instances, maximum 15, and typically 5, which means that each call to .Resolve will either retrieve a service instance from a pool of available objects, or construct a new one. And then, when the IService<T> object that holds the pooled service is disposed of, the service instance is released back into its pool.
Sure, this made all code look like this:
using (var service = ServiceContainer.Global.Resolve<ISomeService>())
{
service.Instance.DoSomething();
}
but it's a clean approach, and it has the same syntax regardless of the type of service or concrete object in use, so we chose that as an acceptable solution.
Original question follows, for posterity
Long-winded question comes here:
We have a IoC container that we use, and recently we discovered what amounts to a problem.
In non-IoC code, when we wanted to use, say, a file, we used a class like this:
using (Stream stream = new FileStream(...))
{
...
}
There was no question as to whether this class was something that held a limited resource or not, since we knew that files had to be closed, and the class itself implemented IDisposable. The rule is simply that every class we construct an object of, that implements IDisposable, has to be disposed of. No questions asked. It's not up to the user of this class to decide if calling Dispose is optional or not.
Ok, so on to the first step towards the IoC container. Let's assume we don't want the code to talk directly to the file, but instead go through one layer of indirection. Let's call this class a BinaryDataProvider for this example. Internally, the class is using a stream, which is still a disposable object, so the above code would be changed to:
using (BinaryDataProvider provider = new BinaryDataProvider(...))
{
...
}
This doesn't change much. The knowledge that the class implements IDisposable is still here, no questions asked, we need to call Dispose.
But, let's assume that we have classes that provide data that right now doesn't use any such limited resources.
The above code could then be written as:
BinaryDataProvider provider = new BinaryDataProvider();
...
OK, so far so good, but here comes the meat of the question. Let's assume we want to use an IoC container to inject this provider instead of depending on a specific concrete type.
The code would then be:
IBinaryDataProvider provider =
ServiceContainer.Global.Resolve<IBinaryDataProvider>();
...
Note that I assume there is an independent interface available that we can access the object through.
With the above change, what if we later on want to use an object that really should be disposed of? None of the existing code that resolves that interface is written to dispose of the object, so what now?
The way we see it, we have to pick one solution:
Implement runtime checking that checks that if a concrete type that is being registered implements IDisposable, require that the interface it is exposed through also implements IDisposable. This is not a good solution
Enfore a constraint on the interfaces being used, they must always inherit from IDisposable, in order to be future-proof
Enforce runtime that no concrete types can be IDisposable, since this is specifically not handled by the code using the IoC container
Just leave it up to the programmer to check if the object implements IDisposable and "do the right thing"?
Are there others?
Also, what about injecting objects in constructors? Our container, and some of the other containers we've looked into, is capable of injecting a fresh object into a parameter to a constructor of a concrete type. For instance, if our BinaryDataProvider need an object that implements the ILogging interface, if we enforce IDispose-"ability" on these objects, whose responsibility is it to dispose of the logging object?
What do you think? I want opinions, good and bad.
One option might be to go with a factory pattern, so that the objects created directly by the IoC container never need to be disposed themselves, eg
IBinaryDataProviderFactory factory =
ServiceContainer.Global.Resolve<IBinaryDataProviderFactory>();
using(IBinaryDataProvider provider = factory.CreateProvider())
{
...
}
Downside is added complexity, but it does mean that the container never creates anything which the developer is supposed to dispose of - it is always explicit code which does this.
If you really want to make it obvious, the factory method could be named something like CreateDisposableProvider().
(Disclaimer: I'm answering this based on java stuff. Although I program C# I haven't proxied anything in C# but I know it's possible. Sorry about the java terminology)
You could let the IoC framework inspect the object being constructed to see if it supports
IDisposable. If not, you could use a dynamic proxy to wrap the actual object that the IoC framework provides to the client code. This dynamic proxy could implement IDisposable, so that you'd always deliver a IDisposable to the client. As long as you're working with interfaces that should be fairly simple ?
Then you'd just have the problem of communicating to the developer when the object is an IDisposable. I'm not really sure how this'd be done in a nice manner.
You actually came up with a very dirty solution: your IService contract violates the SRP, wich is a big no-no.
What I recommend is to distinguish so-called "singleton" services from so-called "prototype" services. Lifetime of "singleton" ones is managed by the container, which may query at runtime whether a particular instance implements IDisposable and invoke Dispose() on shutdown if so.
Managing prototypes, on the other hand, is totally the responsibility of the calling code.