I completely understand what you are trying to do here. You are applying the SOLID principles, so query implementations are abstracted away from the consumer, who merely sends a message (DTO) and gets a result. By implementing a generic interface for the query, we can wrap implementations with a decorator, which allows all sorts of interesting behavior, such as transactional behavior, auditing, performance monitoring, caching, etc, etc.
The way to do this is to define the following interface for a messsage (the query definition):
public interface IQuery<TResult> { }
And define the following interface for the implemenation:
public interface IQueryHandler<TQuery, TResult>
where TQuery : IQuery<TResult>
{
TResult Handle(TQuery query);
}
The IQuery<TResult>
is some sort of marker interface, but this allows us to define statically what a query returns, for instance:
public class FindUsersBySearchTextQuery : IQuery<User[]>
{
public string SearchText { get; set; }
public bool IncludeInactiveUsers { get; set; }
}
An implementation can be defined as follows:
public class FindUsersBySearchTextQueryHandler
: IQueryHandler<FindUsersBySearchTextQuery, User[]>
{
private readonly IUnitOfWork db;
public FindUsersBySearchTextQueryHandler(IUnitOfWork db)
{
this.db = db;
}
public User[] Handle(FindUsersBySearchTextQuery query)
{
// example
return (
from user in this.db.Users
where user.Name.Contains(query.SearchText)
where user.IsActive || query.IncludeInactiveUsers
select user)
.ToArray();
}
}
Consumers can no take a dependency on the IQueryHandler<TQuery, TResult>
to execute queries:
public class UserController : Controller
{
IQueryHandler<FindUsersBySearchTextQuery, User[]> handler;
public UserController(
IQueryHandler<FindUsersBySearchTextQuery, User[]> handler)
{
this. handler = handler;
}
public View SearchUsers(string searchString)
{
var query = new FindUsersBySearchTextQuery
{
SearchText = searchString,
IncludeInactiveUsers = false
};
User[] users = this.handler.Handle(query);
return this.View(users);
}
}
This allows you to add cross-cutting concerns to query handlers, without consumers to know this and this gives you complete compile time support.
The biggest downside of this approach (IMO) however, is that you'll easily end up with big constructors, since you'll often need to execute multiple queries, (without really violating the SRP).
To solve this, you can introduce an abstraction between the consumers and the IQueryHandler<TQuery, TResult>
interface:
public interface IQueryProcessor
{
TResult Execute<TResult>(IQuery<TResult> query);
}
Instread of injecting multiple IQueryHandler<TQuery, TResult>
implementations, you can inject one IQueryProcessor
. Now the consumer will look like this:
public class UserController : Controller
{
private IQueryProcessor queryProcessor;
public UserController(IQueryProcessor queryProcessor)
{
this.queryProcessor = queryProcessor;
}
public View SearchUsers(string searchString)
{
var query = new FindUsersBySearchTextQuery
{
SearchText = searchString
};
// Note how we omit the generic type argument,
// but still have type safety.
User[] users = this.queryProcessor.Execute(query);
return this.View(users);
}
}
The IQueryProcessor
implementation can look like this:
sealed class QueryProcessor : IQueryProcessor
{
private readonly Container container;
public QueryProcessor(Container container)
{
this.container = container;
}
[DebuggerStepThrough]
public TResult Execute<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>)
.MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = container.GetInstance(handlerType);
return handler.Handle((dynamic)query);
}
}
It depends on the container (it is part of the composition root) and uses dynamic
typing (C# 4.0) to execute the queries.
This IQueryProcessor
is effectively your QueryFactory
.
There are downsides of using this IQueryProcessor
abstraction though. For instance, you miss the possibility to let your DI container verify whether a requested IQueryHandler<TQuery, TResult>
implementation exists. You'll find out at the moment that you call processor.Execute
instead when requesting a root object. You can solve this by writing an extra integration test that checks if an IQueryHandler<TQuery, TResult>
is registered for each class that implements IQuery<TResult>
. Another downside is that the dependencies are less clear (the IQueryProcessor
is some sort of ambient context) and this makes unit testing a bit harder. For instance, your unit tests will still compile when a consumer runs a new type of query.
You can find more information about this design in this blog post: Meanwhile… on the query side of my architecture.