I am using the Service / Request / Response pattern. I have for example:
public class FindPostsByTypeRequest : Request { public PostType Type { get; set; } } public class FindPostsByTypeResponse : Response { public IList<PostDto> Posts { get; set; } public class PostDto { public Int32 Id { get; set; } public String Title { get; set; } public String Text { get; set; } } }
To process this request, I have a handler:
public class FindPostsByTypeHandler : Handler<FindPostsByTypeRequest, FindPostsByTypeResponse> { private IContext _context; public FindPostsByTypeHandler(IContext context) { _context = context; } public FindPostsByTypeResponse Handle(FindPostsByTypeRequest request) { IList<FindPostsByTypeRequest.PostDto> posts = _context.Posts .Where(x => x.Type == request.Type) .Select(x => new FindPostsByTypeRequest.PostDto { Id = x.Id, Title = x.Title, Text = x.Text }).ToList(); return new FindPostsByTypeResponse { Posts = posts }; } }
Then I have a dispatcher and use it like this:
FindPostsByTypeRequest request = new FindPostsByTypeRequest { Type = type }; FindPostsByTypeResponse response = _dispatcher.Send<FindPostsByTypeResponse>(request);
The problem I'm trying to solve is :
When I search for messages by type, sometimes I need tags ... Sometimes I do not. Of course, I could always get tags into my DTOs and use them or not ... But you need to avoid downloading something that I don't need ...
So basically I need to get messages by type and "tell" the handler what data I need.
My idea would be something like this:
_dispatcher.Send<FindPostsByTypeResponse<PostWithTagsModel>>(request);
Where PostWithTagsModel will be the DTO that I need. Then in my handler I would:
public class FindPostsByTypeHandler : Handler<FindPostsByTypeRequest, FindPostsByTypeResponse> { private IContext _context; public FindPostsByTypeHandler(IContext context) { _context = context; } public FindPostsByTypeResponse<PostsByType> Handle(FindPostsByTypeRequest request) { IList<FindPostsByTypeResponse.PostDto> posts = _context.Posts .Where(x => x.Type == request.Type) .Select(x => new FindPostsByTypeResponse.PostDto { Id = x.Id, Title = x.Title, Text = x.Text }).ToList(); return new FindPostsByTypeResponse { Posts = posts }; } public FindPostsByTypeResponse<PostsWithoutTagsDto> Handle(FindPostsByTypeRequest request) { IList<FindPostsByTypeResponse.PostsWithoutTagsDto> posts = _context.Posts .Where(x => x.Type == request.Type) .Select(x => new FindPostsByTypeResponse.PostsWithoutTagsDto { Id = x.Id, Title = x.Title, Text = x.Text }).ToList(); return new FindPostsByTypeResponse { Posts = posts }; } public FindPostsByTypeResponse<PostsWithTagsDto> Handle(FindPostsByTypeRequest request) {
I'm not sure if this is possible or even the best way to do this ...
Basically, I need to βtellβ the handler what format I need the DTOs that are included in the response.
How can I or should I do this?