CQRS - Executing Commands within Commands - dependency-injection

I recently saw some code scenarios where CommandHandlers were being injected with ICommandExecutor to call other commands. So commands within commands. This was also true for some QueryHandlers being injected with IQuery.
public class UpdateCarDetailsCommandHandler : CommandHandler<UUpdateCarDetailsCommand>
{
private ICommandExecutor _command;
public UpdateCarDetailsCommandHandler (ICommandExecutor command)
{
_command = command;
}
public override void Execute(UpdateCarDetailsCommand command)
{
//do something with repository
_command.Execute(new CarColour())
}
}
This seems incorrect to me, as the ICommandExecutor would be the composition root in this scenario. Just wondered people thoughts on this?

I say you are correct to be wary of using commands and queries within other commands and queries. Beware abstractions that do too much.
The S in CQRS stands for Segregation. This clearly implies that Commands should remain separate from other Commands and Queries should remain separate from other Queries. But can queries be used by commands? As always, it depends.
Udi Dahan's article from 2009 suggests not:
Since your queries are now being performed off of a separate data store than your master database, and there is no assumption that the data that’s being served is 100% up to date, you can easily add more instances of these stores without worrying that they don’t contain the exact same data.
Dino Esposito recommends using separate projects:
Applying CQRS means you’ll use two distinct middle tiers. One tier takes care of commands that alter the system state. The other retrieves the data. You create a couple of class library projects—query stack and command stack—and reference both from the main Web server project.
My personal view is that you should think of these standard Command and Query handlers as holistic abstractions. A holistic abstraction is an abstraction that is concerned with the whole transaction; it cannot be a dependency within something larger than itself within the confines of a single transaction.
What is needed instead are similar pairs of abstractions that are injectable strategies and that can be decorated with cross-cutting concerns.
E.g.
public interface IDataCommandHandler<TCommand> where TCommand : IDataCommand
{
void Handle(TCommand command);
}
public interface IDataQueryHandler<TQuery, TResult> where TQuery : IDataQuery<TResult>
{
TResult Handle(TQuery query);
}
Or
public interface ICommandStrategyHandler<TCommand> where TCommand : ICommand
{
void Handle(TCommand command);
}
public interface IQueryStrategyHandler<TQuery, TResult> where TQuery : IQuery<TResult>
{
TResult Handle(TQuery query);
}

Related

Entity framework 6 providing repositories and UoW out of the box

But how do you use it?
I have a Code First project set up, and trying out some stuff with this new EF6. Reading all kinds of posts/blogs from at least 2 years old about EF4/5. But nothing whatsoever about EF6.
Let's say I have these entities:
public DbSet<Person> Persons { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Invoice> Invoices { get; set; }
Do I still need to create repositories for each entity? Or would a class suffice with some methods to do some custom calculations aside from CRUD?
I know that this line:
kernel.Bind<MyDbContext>().ToSelf().InRequestScope();
Would suffice for DI, and that it will inject via constructor to upper layer classes where applicable.
The project has a class library and a web project asp.net-mvc. Where the class lib project contains my entities and has Migrations enabled.
Any light on this matter is really appreciated.
I've added a Repository layer on top of EF (which utilizes both Repository and UoW patterns inherently in its construction) in a couple of projects, and I've done that with one class that utilizes generics so that I only needed one file for all of my entities. You can decide if you want to do it or not, but I've found it useful in my projects.
My repositories have typically started out like what I've shown below, following up with more extension methods if/when I come across a need for them (obviously I'm not showing all of them, that's up for you to decide how to implement your repository).
public class Repository<T> : IRepository<T> where T : class
{
protected IDbContext Context;
protected DbSet<T> DbSet { get { return Context.Set<T>(); } }
public Repository(IDbContext context = null)
{
Context = context ?? new DbContext();
}
public void Add(T newRecord)
{
DbSet.Add(newRecord);
}
public void Update(T record)
{
var entry = Context.Entry(record);
DbSet.Attach(record);
entry.State = EntityState.Modified;
}
public void Remove(T record)
{
Context.Entry(record).State = EntityState.Deleted;
DbSet.Remove(record);
}
public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public bool Contains(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate) > 0;
}
public int Count(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate);
}
public int Save()
{
return Context.SaveChanges();
}
}
I've used repositories for 2 main reasons:
Unit testing. Doing this pattern allows me to fake the underlying data without having to have bad data in my database. All I need to do is simply create another implementation of IRepository that uses an in-memory list as its data source, and I'm all set for my pages to query that repository.
Extensibility. A fair number of times I've put in some methods into my repository because I found myself constantly doing the same logic with queries in my controllers. This has been extremely useful, especially since your client-side code doesn't need to know how it's doing it, just that it is doing it (which will make it easier if you need to change the logic of one file vs. multiple files).
This not all of it, obviously, but that should be enough for this answer. If you want to know more on this topic, I did write a blog post on it that you can find here.
Good luck on whatever you decide to do.
Entity Framework in itself can be considered a Repository. It facilitates work with data, in this case a database. This is all that a Repository does.
If you want to build another Repository on top of what EF provides, it is completely up to you - or to your business rules.
Many complex projects uses 2-3 layers of repositories with web services between. The performance is lower but you gain on other plans like security, resilience, separation of concerts, etc.
Your company might decide that it's in their best interest to never access data directly from front-end projects. They might force you to build a separate web-service project, which will be accessible only from localhost. So you will end up having EF as Repository in the webservice project. On the front-end side you will obviously need to build another Repository which will work with the web-service.
It also depends a lot of your project. If it's a small project it really it's overkill to build a second Repository on top of EF. But then again, read above. Nowadays security matters a lot more than performance.
To be politically correct I'm including the comment made by Wiktor Zychla:
"DbSet is a repository and DbContext is a Unit of Work. "Entity Framework is a Repository" could lead to unnecessary confusion."

ICommandHandler/IQueryHandler with async/await

EDITH says (tl;dr)
I went with a variant of the suggested solution; keeping all ICommandHandlers and IQueryHandlers potentially aynchronous and returning a resolved task in synchronous cases. Still, I don't want to use Task.FromResult(...) all over the place so I defined an extension method for convenience:
public static class TaskExtensions
{
public static Task<TResult> AsTaskResult<TResult>(this TResult result)
{
// Or TaskEx.FromResult if you're targeting .NET4.0
// with the Microsoft.BCL.Async package
return Task.FromResult(result);
}
}
// Usage in code ...
using TaskExtensions;
class MySynchronousQueryHandler : IQueryHandler<MyQuery, bool>
{
public Task<bool> Handle(MyQuery query)
{
return true.AsTaskResult();
}
}
class MyAsynchronousQueryHandler : IQueryHandler<MyQuery, bool>
{
public async Task<bool> Handle(MyQuery query)
{
return await this.callAWebserviceToReturnTheResult();
}
}
It's a pity that C# isn't Haskell ... yet 8-). Really smells like an application of Arrows. Anyway, hope this helps anyone. Now to my original question :-)
Introduction
Hello there!
For a project I'm currently designing an application architecture in C# (.NET4.5, C#5.0, ASP.NET MVC4). With this question I hope to get some opinions about some issues I stumbled upon trying to incorporate async/await. Note: this is quite a lengthy one :-)
My solution structure looks like this:
MyCompany.Contract (Commands/Queries and common interfaces)
MyCompany.MyProject (Contains the business logic and command/query handlers)
MyCompany.MyProject.Web (The MVC web frontend)
I read up on maintainable architecture and Command-Query-Separation and found these posts very helpful:
Meanwhile on the query side of my architecture
Meanwhile on the command side of my architecture
Writing highly maintainable WCF services
So far I've got my head around the ICommandHandler/IQueryHandler concepts and dependency injection (I'm using SimpleInjector - it's really dead simple).
The Given Approach
The approach of the articles above suggests using POCOs as commands/queries and describes dispatchers of these as implementations of the following handler interfaces:
interface IQueryHandler<TQuery, TResult>
{
TResult Handle(TQuery query);
}
interface ICommandHandler<TCommand>
{
void Handle(TCommand command);
}
In a MVC Controller you'd use this as follows:
class AuthenticateCommand
{
// The token to use for authentication
public string Token { get; set; }
public string SomeResultingSessionId { get; set; }
}
class AuthenticateController : Controller
{
private readonly ICommandHandler<AuthenticateCommand> authenticateUser;
public AuthenticateController(ICommandHandler<AuthenticateCommand> authenticateUser)
{
// Injected via DI container
this.authenticateUser = authenticateUser;
}
public ActionResult Index(string externalToken)
{
var command = new AuthenticateCommand
{
Token = externalToken
};
this.authenticateUser.Handle(command);
var sessionId = command.SomeResultingSessionId;
// Do some fancy thing with our new found knowledge
}
}
Some of my observations concerning this approach:
In pure CQS only queries should return values while commands should be, well only commands. In reality it is more convenient for commands to return values instead of issuing the command and later doing a query for the thing the command should have returned in the first place (e.g. database ids or the like). That's why the author suggested putting a return value into the command POCO.
It is not very obvious what is returned from a command, in fact it looks like the command is a fire and forget type of thing until you eventually encounter the weird result property being accessed after the handler has run plus the command now knows about it's result
The handlers have to be synchronous for this to work - queries as well as commands. As it turns out with C#5.0 you can inject async/await powered handlers with the help of your favorite DI container, but the compiler doesn't know about that at compile time so the MVC handler will fail miserably with an exception telling you that the method returned before all asynchronous tasks finished executing.
Of course you can mark the MVC handler as async and this is what this question is about.
Commands Returning Values
I thought about the given approach and made changes to the interfaces to address issues 1. and 2. in that I added an ICommandHandler that has an explicit result type - just like the IQueryHandler. This still violates CQS but at least it is plain obvious that these commands return some sort of value with the additional benefit of not having to clutter the command object with a result property:
interface ICommandHandler<TCommand, TResult>
{
TResult Handle(TCommand command);
}
Naturally one could argue that when you have the same interface for commands and queries why bother? But I think it's worth naming them differently - just looks cleaner to my eyes.
My Preliminary Solution
Then I thought hard of the 3rd issue at hand ... some of my command/query handlers need to be asynchronous (e.g. issuing a WebRequest to another web service for authentication) others don't. So I figured it would be best to design my handlers from the ground up for async/await - which of course bubbles up to the MVC handlers even for handlers that are in fact synchronous:
interface IQueryHandler<TQuery, TResult>
{
Task<TResult> Handle(TQuery query);
}
interface ICommandHandler<TCommand>
{
Task Handle(TCommand command);
}
interface ICommandHandler<TCommand, TResult>
{
Task<TResult> Handle(TCommand command);
}
class AuthenticateCommand
{
// The token to use for authentication
public string Token { get; set; }
// No more return properties ...
}
AuthenticateController:
class AuthenticateController : Controller
{
private readonly ICommandHandler<AuthenticateCommand, string> authenticateUser;
public AuthenticateController(ICommandHandler<AuthenticateCommand,
string> authenticateUser)
{
// Injected via DI container
this.authenticateUser = authenticateUser;
}
public async Task<ActionResult> Index(string externalToken)
{
var command = new AuthenticateCommand
{
Token = externalToken
};
// It's pretty obvious that the command handler returns something
var sessionId = await this.authenticateUser.Handle(command);
// Do some fancy thing with our new found knowledge
}
}
Although this solves my problems - obvious return values, all handlers can be async - it hurts my brain to put async on a thingy that isn't async just because. There are several drawbacks I see with this:
The handler interfaces are not as neat as I wanted them to be - the Task<...> thingys to my eyes are very verbose and at first sight obfuscate the fact that I only want to return something from a query/command
The compiler warns you about not having an appropriate await within synchronous handler implementations (I want to be able to compile my Release with Warnings as Errors) - you can overwrite this with a pragma ... yeah ... well ...
I could omit the async keyword in these cases to make the compiler happy but in order to implement the handler interface you would have to return some sort of Task explicitly - that's pretty ugly
I could supply synchronous and asynchronous versions of the handler interfaces (or put all of them in one interface bloating the implementation) but my understanding is that, ideally, the consumer of a handler shouldn't be aware of the fact that a command/query handler is sync or async as this is a cross cutting concern. What if I need to make a formerly synchronous command async? I'd have to change every consumer of the handler potentially breaking semantics on my way through the code.
On the other hand the potentially-async-handlers-approach would even give me the ability to change sync handlers to be async by decorating them with the help of my DI container
Right now I don't see a best solution to this ... I'm at a loss.
Anyone having a similar problem and an elegant solution I didn't think of?
Async and await don't mix perfectly with traditional OOP. I have a blog series on the subject; you may find the post on async interfaces helpful in particular (though I don't cover anything you haven't already discovered).
The design problems around async are extremely similar to the ones around IDisposable; it's a breaking change to add IDisposable to an interface, so you need to know whether any possible implementation may ever be disposable (an implementation detail). A parallel problem exists with async; you need to know whether any possible implementation may ever be asynchronous (an implementation detail).
For these reasons, I view Task-returning methods on an interface as "possibly asynchronous" methods, just like an interface inheriting from IDisposable means it "possibly owns resources."
The best approach I know of is:
Define any methods that are possibly-asynchronous with an asynchronous signature (returning Task/Task<T>).
Return Task.FromResult(...) for synchronous implementations. This is more proper than an async without an await.
This approach is almost exactly what you're already doing. A more ideal solution may exist for a purely functional language, but I don't see one for C#.
You state:
the consumer of a handler shouldn't be aware of the fact that a
command/query handler is sync or async as this is a cross cutting
concern
Stephen Clearly already touched this a bit, but async is not a cross-cutting concern (or at least not the way it's implemented in .NET). Async is an architectural concern since you have to decide up front to use it or not, and it completely chances all your application code. It changes your interfaces and it's therefore impossible to 'sneak' this in, without the application to know about it.
Although .NET made async easier, as you said, it still hurts your eyes and mind. Perhaps it just needs mental training, but I'm really wondering whether it is all worth the trouble to go async for most applications.
Either way, prevent having two interfaces for command handlers. You must pick one, because having two separate interfaces will force you to duplicate all your decorators that you want to apply to them and duplicates your DI configation. So either have an interface that returns Task and uses output properties, or go with Task<TResut> and return some sort of Void type in case there is no return type.
As you can imagine (the articles you point at are mine) my personal preference is to have a void Handle or Task Handle method, since with commands, the focus is not on the return value and when having a return value, you will end up having a duplicate interface structure as the queries have:
public interface ICommand<TResult> { }
public interface ICommandHandler<TCommand, TResult>
where TCommand : ICommand<TResult>
{
Task<TResult> Handle(TCommand command);
}
Without the ICommand<TResult> interface and the generic type constraint, you will be missing compile time support. This is something I explained in Meanwhile... on the query side of my architecture
I created a project for just this - I wound up not splitting commands and queries, instead using request/response and pub/sub - https://github.com/jbogard/MediatR
public interface IMediator
{
TResponse Send<TResponse>(IRequest<TResponse> request);
Task<TResponse> SendAsync<TResponse>(IAsyncRequest<TResponse> request);
void Publish<TNotification>(TNotification notification) where TNotification : INotification;
Task PublishAsync<TNotification>(TNotification notification) where TNotification : IAsyncNotification;
}
For the case where commands don't return results, I used a base class that returned a Void type (Unit for functional folks). This allowed me to have a uniform interface for sending messages that have responses, with a null response being an explicit return value.
As someone exposing a command, you explicitly opt-in to being asynchronous in your definition of the request, rather than forcing everyone to be async.
Not really an answer, but for what it's worth, i came to the exact same conclusions, and a very similar implementation.
My ICommandHandler<T> and IQueryHandler<T> return Task and Task<T> respectively. In case of a synchronous implementation i use Task.FromResult(...). I also had some *handler decorators in place (like for logging) and as you can imagine these also needed to be changed.
For now, i decided to make 'everything' potentially await-able, and got into the habit of using await in conjunction with my dispatcher (finds handler in ninject kernel and calls handle on it).
I went async all the way, also in my webapi/mvc controllers, with few exceptions. In those rare cases i use Continuewith(...) and Wait() to wrap things in a synchronous method.
Another, related frustration i have is that MR recommends to name methods with the *Async suffix in case thay are (duh) async. But as this is an implementation decision i (for now) decided to stick with Handle(...) rather than HandleAsync(...).
It is definitely not a satisfactory outcome and i'm also looking for a better solution.

What are good ways to reduce the number of dependencies?

I am using dependency injection for quite some time and I really like the technique, but I often have a problem of too many dependencies that should be injected 4 - 5 which seems to much.
But I cannot find a way to make it simpler. For instance I have a class with some business logic that sends messages, it accepts two other business logic dependencies to do what is needed (one to translate data to messages sent, and one to translate messages that are received).
But apart from this it needs some "technical" dependencies like ILogger, ITimerFactory (because it needs to create timers inside), IKeyGenerator (to generate unique keys).
So the whole list grows pretty big. Are there any good common ways to reduce the number of dependencies?
One way to handle those is to refactor towards Aggregates (or Facades). Mark Seemann wrote a good article on it, check it out (actually I highly recommend his book as well, just saying).
So say you have the following (as taken from the article):
public OrderProcessor(IOrderValidator validator,
IOrderShipper shipper,
IAccountsReceivable receivable,
IRateExchange exchange,
IUserContext userContext)
You can refactor it to:
public OrderProcessor(IOrderValidator validator,
IOrderShipper shipper,
IOrderCollector collector)
Where OrderCollector is a facade (it wraps the previous 3 dependencies):
public OrderCollector(IAccountsReceivable receivable,
IRateExchange exchange,
IUserContext userContext)
I hope this helps.
EDIT
In terms of the cross-cutting concerns (logging and caching for example) and a strategy to handle them, here is a suggestion (that's what I usually do), say you have the following:
public interface IOrderService
{
void DoAwesome();
}
public class OrderService : IOrderService
{
public void DoAwesome()
{
// do your thing here ... no logging no nothing
}
}
Here I'd use the decorator pattern to create an OrderService that has logging enabled:
public class OrderServiceWithLogging : IOrderService
{
private readonly IOrderService _orderService;
private readonly ILogger _logger;
public OrderServiceWithLogging(IOrderService orderService, ILogger logger)
{
_orderService = orderService;
_logger = logger;
}
public void DoAwesome()
{
_orderService.DoAwesome();
_logger.Log("Awesome is done!");
}
}
It might look like a bit of overhead but IMHO, it's clean and testable.
Another way would be to go into Aspect Oriented Programming and look into concepts such as interception, where basically you intercept certain method calls and perform tasks as a result. Many DI frameworks (I wanna say all?) support interception, so that might be something that you prefer.

Dependency Injection + Ambient Context + Service Locator

Recently I was reading a lot of stuff about application design patterns: about DI, SL anti-pattern, AOP and much more. The reason for this - I want to come to a design compromise: loosely coupled, clean and easy to work with. DI seems ALMOST like a solution except one problem: cross-cutting and optional dependencies leading to constructor or property pollution. So I come with my own solution for this and I want to know what do you think of it.
Mark Seemann (the author of DI book and famous "SL is anti-patter" statement) in his book mentions a pattern called Ambient Context. Though he says he doesn't like it much, this pattern is still interesting: it's like old good singleton except it is scoped and provide default value so we don't have to check for null. It has one flaw - it doesn't and it can't know about it's scope and how to dispose itself.
So, why not to apply Service Locator here? It can solve problem of both scoping and disposing of an Ambient Context objects. Before you say it's anti-pattern: it is when you hide a contract. But in our case we hide OPTIONAL contract, so it's not so bad IMO.
Here some code to show what I mean:
public interface ILogger
{
void Log(String text);
}
public interface ISomeRepository
{
// skipped
}
public class NullLogger : ILogger
{
#region ILogger Members
public void Log(string text)
{
// do nothing
}
#endregion
}
public class LoggerContext
{
public static ILogger Current
{
get
{
if(ServiceLocator.Current == null)
{
return new NullLogger();
}
var instance = ServiceLocator.Current.GetInstance<ILogger>();
if (instance == null)
{
instance = new NullLogger();
}
return instance;
}
}
}
public class SomeService(ISomeRepository repository)
{
public void DoSomething()
{
LoggerContext.Current.Log("Log something");
}
}
Edit: I realize that asking not concrete question goes in conflict with stack overflow design. So I will mark as an answer a post best describing why this design is bad OR better giving a better solution (or maybe addition?). But do not suggest AOP, it's good, but it's not a solution when you really want to do something inside your code.
Edit 2: I added a check for ServiceLocator.Current is null. It's what I intent my code to do: to work with default settings when SL is not configured.
You can add cross-cutting concerns using hand-crafted decorators or some kind of interception (e.g. Castle DynamicProxy or Unity's interception extension).
So you don't have to inject ILogger into your core business classes at all.
A problem with an ambient context as the one you propose, is that it makes testing much harder. For a couple of reasons:
While running your unit tests, there must always be a valid instance registered in "ServiceLocator.Current". But not only that, it must be registered with a valid ILogger.
When you need to use a fake logger in a test (other than the simple
NullLogger), you will have to configure your container, since there
is no way in hooking into this, but since the container is a singleton, all other tests will use that same logger.
It will be non-trivial (and a waste of time) to create a solution that works when your unit tests are run in parallel (as MSTest does by default).
All these problems can be solved by simply injecting ILogger instances into services that need it, instead of using a Ambient Context.
And if many classes in your system depend on that ILogger abstraction, you should seriously ask your self whether you're logging too much.
Also note that dependencies should hardly ever be optional.

MVC: What's better, one large repository per db or one per business entity?

This time I have a more philosopical question.
Most MVC tutorials/books seem to suggest to restrict the scope of one repository to one aspect of the model and set up multiple repositories to cover all model classes. (E.g.: ProjectRep, UserRep, ImageRep, all mapping onto the same db eventually.)
I can see how that would make unittesting simpler but I can't imagine how this would work in the real world, where most entities have relationships between each other. In the end I always find myself with one gigantic repository class per DB connection and an equally arkward FakeRepository for unittesting.
So, what's your opinion? Should I try harder to seperate out repositories? Does it even matter if the ProductRep refers to data in the UserRep and vice versa via PurchaseHistory? How would the different reps make sure they don't lock each other up when accessing the single db?
Thanks,
Duffy
This works in the real world because there's single engine under the hood of the repositories. This can be ORM like NHibernate or your own solution. This engine knows how to relate objects, lock database, cache requests, etc. But the business code shouldn't know these infrastructure details.
What you effectively do when you end up with one giantic repository is exposing this single engine to the real world instead. Thus you mess your domain code with engine-specific details that are otherwise hidden behind repository interfaces.
S#arp Architecture is a very good illustration of how repositories that Josh talk about are implemented and work. Also read the NHibernate best practices article that explains much of S#arp background.
And frankly, I can't imagine how your giantic repository works in the real world. Because the very idea looks bad and unmaintainable.
I've found that by using generics and an interface, you can avoid having to code many separate repositories. If your domain model is well-factored, you can often navigate object graphs using the domain objects rather than another repository.
public class MyDomainObject : IEntity //IEntity is an arbitrary interface for base ents
{
public int Id { get; set;}
public List<DiffObj> NavigationProp { get; set;}
//... and so on...
}
public interface IRepository<T> where T : IEntity, class, new()
{
void Inert(T entity);
T FindById(int id);
//... and so on
}
The usage is pretty simple, and by using IoC you can completely decouple implementation from the rest of your application:
public class MyBusinessClass
{
private IRepository<SomeDomainObject> _aRepo;
public MyBusinessClass(IREpository<SomeDomainObject> aRepo)
{
_aRepo = aRepo;
}
//...and so on
}
This makes writing unit tests a real snap.

Resources