-
Notifications
You must be signed in to change notification settings - Fork 3
why command routing
Using MVC and WebApi, requests get mapped to action methods on controller classes. Those controllers can have multiple action methods (indeed they usually do) and those methods can accept an arbitrary number of parameters.
For example, consider the following controller:
public class SignInController : ApiController
{
private readonly IAuthenticator _authenticator;
private readonly IUserSession _userSession;
public SignInController(IAuthenticator authenticator, IUserSession userSession)
{
_authenticator = authenticator;
_userSession = userSession;
}
// POST api/signin
public void Post([FromBody]SignInRequest signInRequest)
{
IUser user;
bool authenticated = _authenticator.Authenticate(signInRequest, out user);
if (authenticated)
_userSession.SignIn(user);
}
// DELETE api/signin
public void Delete()
{
_userSession.SignOut();
}
}
Now consider how you would test the Delete
method on this controller, which signs the user out. In order to test this method we first need to create a SignInController
with two dependencies:
IAuthenticator
IUserSession
This is weird. The Delete
method doesn't actually use IAuthenticator
however we have to supply this because the Post
method does need it.
It would be possible to work around this by specifying the dependencies as properties rather than constructor arguments, but then our dependencies are no longer explicit - you have to actually look at the code to know which methods require what and therefore what dependencies you need to supply in order to call any particular method.
Using Command Routing however, each route has it's own separate request pipeline and so you only need to provide the dependencies that are absolutely necessary to handle the specific command or query that you're dealing with and those dependencies are explicit. Command Routes don't come with extra baggage.