Message Driven Architecture Explained: Eventual Consistency and Saga

By Mike on 30 April 2013

You can find part one here

Let's talk about the really interesting stuff about Message Driven Architecture (MDA).

Eventual Consistency

Most of the time you might use a RDBMS which enforces consistency and you know that if the transaction has been committed, everything is saved. When dealing with distributed components availble on different servers, suddenly you can't use this feature. The same problem appears in a local application when you're using NoSql db or you have to save data in 2 databases belonging to a RDBMS or you have 2 or more incompatible data storage (for example: file system and rdbms).

With MDA you need get used to eventual consistency which can be explained very simply: everything will be consistent.. eventually. The thing is, a model is consistent at one moment in time. For example, a web page shows some data. The data is a valid model until you refresh the page. If you don't refresh it then for you the model doesn't change, even if on server it's already different. However, eventually, you will refresh the page and you'll get the latest model which of course might change 1ms after the page loaded.

Eventual consistency is everywhere around us, we all work with obsolete data, but the RDBMS have spoiled us to think that we can have always access to the latest, accurate and 'true' data. This works when using only one RDBMS but that's it. Change that condition and we're back to the real world where everything gets stale after a second. Embracing (the natural) eventuality is required for MDA and it's not that hard to get used to it, actually.

So, how do we deal with it? Well, quite simple actually. Since in MDA every business object is modified as the result of a command, it means that the commands themselves need to be committed together as a unit of work. Every ServiceBus has the feature to send more messages at once. This is the 'transaction'. Note that the important part is that the commands will be received together, but that doesn't mean they will be handled at the same time. But this doesn't matter as they will be all handled eventually :)

Saga

A Saga is used to manage a long running process. Got it? No? Well, there are some long running operations which are considered to be complete when all their steps are completed. Nothing unusual except the fact that each step can be completed independently of other so there isn't a predefined order. Another aspect is that steps are completed in unknown time periods, so one can take 2ms while others minutes, hours or days. The saga keeps track of these steps as they happen and ends when all involved steps are completed.

Let's consider this real-life example: John goes to a fast food restaurant and orders a menu. This means one hamburger, one portion of fries and one soda. John tries to pays with the credit card... if he finds it. For whatever reason, it's not in the usual place. In the mean time, the employee get the soda and tells John he has to wait a bit for the hamburgers and the fries. John finally finds the credit card and pays. After a few minutes everything is ready and he can enjoy his meal.

Now, in this example we don't care much about John (sorry!) but we care about the operation as seen from the restaurant point of view. The operation is complete when the whole menu is ready and paid for by the customer. We have the following steps:
- Hamburger ready;
- Fries ready;
- Soda ready;
- Payment received.

The important thing here is that any of these can be completed in any order. Remember in our example that the order was:
- Soda ready
- Payment received
- Hamburger ready
- Fries ready

Usually things probably happen in a slightly different order depending on how you pay and if the menu items are already prepared.

Now, let's 'write' the above example as a saga.

John orders a menu, that is the OrderSubmitted event is published which starts the operation (saga). Starting the saga means issuing the commands: PrepareHamburger, PrepareFries, PrepareSoda, ReceivePayment. It just happens that E will handle all the commands: first E checks for each menu item to see if they are available. Hamburgers and Fries are not so two other commands MakeHamburger and MakeFries are sent. The Soda is available, so the SodaReady event can be published which signals the saga that one step has been completed.

In the mean time John pays so the PaymentReceived event is published and saga marks another step as completed. After a few minutes the HamburgerReady and FriesReady events arrive and the saga marks the last items' completition. All the steps are completed so saga ends, preferably with the SentOrderToClient command.

Here we have 2 actors: the employee (which is the messages handler) and the saga. A saga is started by an event and it's updated by other events. All these need to be correlated so there is usually a message property which acts as the correlation id (for example OrderId). All that saga does is to coordinate events and commands. In the above example, saga began by sending a few commands then handled the events which updated its progress and when it completed, it sent a final command.

In this example 'long running'  meant a few minutes. But consider the case where you order something online, you pay now but the seller may get the payment confirmation after 5 minutes, the items will be available in 3 days and you'll get the products delivered after 1 more day. The PrepareForDeliverySaga starts with OrderSubmitted and ends when both PaymentReceived and ProductsInStock events are published. The saga may end with a ShipProducts command which will generate a OrderShipped event which in turn may start a ShippingSaga which ends when the customer has received and signed for the goods. Or you can include the OrderShipped and OrderDelivered steps in the first saga.

And this should be all, I hope now you have a better understanding of what Eventual Consistency and Saga are.

Benefits Of Using A DI Container

By Mike on 10 April 2013

The good news about writing a trivial app is that you don't need many things. Only some basic coding skills and a 'get it done' attitude. Design patterns, SOLID code etc are not required. It's code and forget. Easy and practical.

However, when dealing even with moderately complex apps things are different: there is advanced functionality required and changes are the norm. Suddenly, the way the app is designed and how the code is written matters. At that point, we care a lot about maintainability, which implies decoupled code. And decoupled code means that most objects will take one or more abstract dependencies.

So we have objects which require dependencies. That's not a problem as it's easy to provide those dependencies manually. Unless those dependencies themselves require dependencies and so on. At that point, a manual solution becomes cumbersome. A better, automated solution is needed and here is where the DI Container comes into play.

There is a saying among developers: "When learning about DI Container you don't understand why you really need it, but after you start using it properly, you wonder how you managed without one".

The most obvious benefit of a DI Container is the automated wiring of all dependencies. 1 or 100 it doesn't matter, the Container knows how to provide them. It's almost magical. But the benefits don't stop here.

Fact is, a Container is a factory which creates objects on demand. But it doesn't just creates them, it can also manage their lifetime which is an important feature. You might be aware that the Singleton pattern can be viewed as an anti pattern, mainly because of the static property which messes up testing and multi-threading scenarios. Oh, and breaking the Single Responsibility Principle, because the object gets the additional task to handle its own lifetime.

Using a Container, you just tell it to treat an object as a singleton so the same instance will be used every time. The object itself doesn't know that it'll be used as a singleton so there's no need for private constructors or static properties. The object is relieved of the task to manage its own lifetime. You get less code and increased testability.

But that's not all, as you can set the Container to return the same instance for a defined scope, for example a request in a web app. Any time the object is needed in that scope, you know there will be the same instance. And speaking of scope, most Containers knows how to handle IDisposable, so when the scope ends any disposable object will be disposed as well.

Containers are also useful when you have interfaces (abstractions) defined and you need instances of concrete but unkown types. This is the a very common usage in business applications which, for example, define abstractions for business rules then need the actual implementations. With a Container you just register all types implementing the interface (every Container has a method to scan and register types matching a criteria). Then the business rules engine asks the Container for instances of types implementing a certain interface (or just takes a dependency on a List<IBusinessRule>) and uses them. The benefit is that you can add lots of business rules implementations (new types) and they will be automatically used without needing to change or to add any other code. And the important detail is that at least some of the concrete objects have one or more dependencies.

When you have a complex app, you have lots of code, especially lots of objects. A Container makes it easier to achieve low coupling and lets you focus on proper object design as you don't have to deal with object instantiation or dependency lifetime. Of course, you will instantiate manually a lot of objects, but none of them will be a dependency.

Now, the most common antipattern when using a Container is something like this

public class MyClass
{
   public MyClass()
   {
      var dep1=Container.Resolve<Dependency>();
   }
}

This code invalidates the use of a Container because:

  1.  MyClass is tightly coupled to the container
  2. None of its dependencies are actualy injected

The proper code should look like this

public class MyClass
{
   public MyClass(IDependency dep)
   {
     //assign dep to field
   }
}

MyClass doesn't know that a Container is used, it knows only about an abstract dependency. It's the usually the job of a framework to call the Container for an instance of MyClass. In your code you should try to refer to the Container as little as possible so that very little code should actually depend on the Container itself.

Good code knows only about its immediate dependencies and those should be abstractions. When an object requires an outside object which is not injected as a dependency, you have a tight coupling problem. So use only the injected dependencies and let the Container do the wiring.

P.S: Some Containers feature Interceptions which are used to implement Aspect Oriented Programming (AOP). In my opinion, this is an optional feature that isn't directly related to the main job a DI Container does. An AOP dedicated framework is a better choice.

Do We Need The Repository Pattern?

By Mike on 10 October 2012

Just when I thought I've covered anything related to the Repository Pattern, Jimmy Boggard writes this and this . Since I consider the Repository Pattern the easy and intuitive way of dealing with storage concerns, I'm always baffled how other devs seem to consider it a complication or not needed. I'm really starting to ask myself if I've understood the pattern correctly. But even if my view of the pattern is -let's say - extended and maybe it's actually another pattern or a combination, I still find it the most natural way of abstracting the persistence.

One thing I keep seeing popping up is the if you're using an ORM what's the point of the repository? You can read my post Repository vs ORM for more details, but in short, the ORM only 'hides' a handful of RDBMS. Change the RDMBS to a NoSql and the ORM becomes useless. Yes, you might not change the db very often but the point of a repository is not to hide a db engine, it's to abstract the whole storage.

In an application, you might deal with different storage at once: local db, xml files, cloud storage etc. The Repository pattern hides all those and gives to the rest of the app an interface: get me this, save that. Where and how is not the app's problem.

Let's work a bit on Jimmy's example. We have the simple case of a blog engine and a controller action which returns a list of posts. But querying the RavenDb in the controller is ugly (hard to maintain - fat controller symptom) and the elegant solution is to use a query object which encapsulates the actually query, pretty much a facade.

For me this approach is actually a bit of the repository pattern, because that why you're using a repository in the first place. Yes, to abstract anything storage related and to provide a facade that makes sense from the business point of view. A 'GetPosts' method says more that a 5 lines long Linq. It helps with maintainability.

But about those repositories with dozens of methods? Well, split them. That's why you're using interfaces, are you telling me that you'll use all those methods in one controller? If so, then that repository is actually needed for that controller. But if the controller only uses 2-3 methods, extract an interface and use only that.

Furthermore, a repository usually serves a bounded context. The PostsRepository from the Domain is very different than the PostsRepository from the UI (different bounded contexts). The latter is usually named something like PostsQueriesRepository PostsViewModelsRepository(in fact it will be an IQueryPosts interface) to avoid confusion.

I was asked a few times, what's the difference between a repository and a DAL interface. The repository is a high level concept  used to access the persistence. It's implemented in code first as an interface (most of the time) defined where(in any layer) you need it. The actual repositories implementations reside in the DAL (Persistence Layer). And you can say that a repository contract is an entry/exit point of DAL, while its implementation is a a part of DAL. So the DAL is made up from ALL the repositories and ALL of DAOs, ORMs, ORM entities and utilities, pretty much everything directly related to accessing the storage.

It seems that most of the devs are considering a Repository just a way of hiding a db or worse, a wrapper over the ORM. It's a bit more than that, it's a high level abstraction which helps separate the Persistence Layer from the rest of the app. It also provides a meaningful facade from the business point of view, thus helping with maintainability.

Repository Pattern Revisited With An Example Of Advanced Usage

By Mike on 18 July 2012

I've described the Repository Pattern in a previous post. Those things are still valid but I want to emphasize a few aspects and to present a scenario of advanced usage.

First of all, it seems to me that way to many developers believe the Repository is there just to hide the database.Probably that's why a number of them don't understand why you need a repository when you have an ORM. Hiding the db is just one function of the Repository as it does other, more important things.

We know that the rest of the application talks to a repository when it wants something persistence related. The Application sends and receives application objects (business objects and DTOs for the view model) from the Repository, without caring what the repo uses to actual store the objects. In the majority of cases, it will probably use a (micro)ORM like EF or NH, but no matter the underlying library, the repo has to return or to handle application objects that have no relation to an ORM's entity.

This means that the Repository must 'translate' application objects to ORM entities and vice versa. The repository is pretty much like a criogenic machine: it takes something and freezes it and then unfreezes it when asked, returning a perfectly valid object exactly as it was received. So the Repository has a more active role than just simply hiding a storage device, the repository IS the governor of persistence

There isn't just a single Repository either. There are as many repositories as bounded contexts, because a repository should serve only a specific context. It might be related to persisting Domain entities or just to query and return view models , the important thing is that there are as many repositories as needed by the application.

I've said above that a repository sends back a business object when asked. But if the object is saved in 3 related tables, how does the Repository knows how to construct it? That's easy, Mike, just pass a factory to the repository's constructor and let the factory handle it. Well, I think this approach might not be the right one for 90% of the cases and that's because a repository restores an object, it doesn't create a new one. Semantics I know, but they do matter. I think it's important to make the distinction between restoring and creating a new object, especially when dealing with Aggregate Roots.

There are a number of ways to restore a complex object, I favor two:

  •  save and load a memento (a dto containing the object state) and then pass it via the object constructor, which can be a static factory method of the object;
  •  use Event Sourcing and store everything a a stream of events. When restoring the object, just pass the stream as constructor argument (this is the standard way to restore an object using ES).

When dealing with queries, things are even simpler: the repository returns a DTO and there are a number of ways to get one.This is a trivial matter and outside this post.

Advanced Usage

Now let's go a bit deeper into the rabbit hole and let's use the repository in a more advanced way. For simplicity let's consider this scenario: we have a blog (yes..) with posts and pages. Both support visibility options: they can be public or private.

public interface IVisibility
{
     int Id {get;}
	 bool IsPublic {get;set;}
}

public class Post: IVisibility { }

public class Page: IVisibility {}

When creating a post or a page we can set their visibility but we want to to that after wards, from the admin page. Assuming we use a task based UI, this means that a request is sent to the server to change visibility for the item with id=5.

But , what do we ask the Repository for? A post, a page? How about we ask it to give us an object for which we can change the visibility? It is pretty much what we want, we don't really care if it's a post or a page, it's an item you want to make private. So how about this?

var item=repository.WantToChangeVisiblility(id);
item.IsPublic=false;
repository.Save(item);

public interface IRepository
{
   IVisibility WantToChangeVisibility(int id);
   void Save(IVisibility item);
}

What do you see? It's obvious that the intention is very clear, also the app receives an object which allows one thing only. If the repository would have returned a Post or a Page object we would have 2 issues:

  •  An explicit Post/Page will alow you to do more that change visibility. And maybe you don't have areason to do that now, but give it time. And if you don;t find a reason, I'm sure a junior developer working with that code will find one in no time.
  •  The repository must populate a whole business object which, depending on the desired action, can be just waste of resources. In this example, why should it load a Post with all the details and 300 comments, just to modify its visibility?!

Ok, all interesting and that, but how do we implement it in the repository? Like this:

internal class ItemWithVisibility:IVisibility{}

This class is defined in the DAL, it's an implementation detail. When the app asks for an IVisibility, the repository returns an instance of ItemWithVisibility containing only the relevant information. Easy and lightweight. And by the way, this simple object can be considered the Aggregate Root for that context. Of course, you might have a fully AR defined in the Domain which will look the same. Note that the AR is simply the object 'representing' a bounded context, it doesn't need tot be complex it that particular context doesn't require it.

This is an elegant way to use the repository in synergy with the rest of the app. It's a waste to treat the repository just as a simple dumb wrapper to hide the db, it can do more for your application.

Elegant Domain Events Setup In Asp.Net Mvc

By Mike on 13 June 2012

I consider the Domain Events Pattern an elegant way of communicating between layers with minimum of coupling and I even coded a light library for it (Domain Events Toolkit). I'm using both the pattern and the library in Fulldot to handle some operations.


Best example is when a user submit a comment. One the comment is saved you want to notify the admin or the post author , usually via an email. Other example is the Pingback functionality, after writing a post the pingback module searches the content for urls and tries to ping them. These kinds of operations are performed as a result of a domain update.

The steps are usually these:
- Create the event and the event handler types
- register the event handler
- raise event
- event is handled
- cleanup

In a web application, since every request executes independently, the handlers make sense only for dome actions and this means you have something like this (using Domain Events Toolkit)

public class CommentSubmittedEvent:IDomainEvent
{
    /* ... implementation ... */
}

public class SendEmailAfterCommentHandler:DomainEventHandlerBase<CommentSubmittedEvent>
{
  /* constructor with dependencies, implementation */
}


//in the controller
 public ActionResult AddComment(AddCommentModel model)
        {
            var sendEmail= new SendEmailAfterCommentHandler(_repository);
			using (_events.RegisterHandler(sendEmail))
			 {
			      var cmd = Fulldot.FactoryCreate.AddCommentCommand(model, this.GetUserContext(), Request.UserHostAddress);
				  this.Handle(cmd);
			 }
			
        }

A bit of explanation is required for the controller. Aside Domain Events I also use a Command based architecture to update the domain. The first line just creates that command. The second sends the command to a command handler which will actually do the real work.  The command handler is setup in the Container, while the 'Handle' method is provided by CavemanTools Mvc. In a nutshell it will ask the Container for a handler for the command, then it will execute it.

Once the command has been executed, a new domain event is raised , which will be handled by an instance of LocalDomainEventManager (the _events variable) provided by the Domain Events Toolkit. While it's pretty clean, things will go much uglier if you want to setup more handlers for the event. For example, after changing a post, besides the Pingback I want the post processed by Lucene.Net (or another full text search service). We have 2 handlers now and the code will get uglier, all because of the setup of the handlers.

And in fairness, this is an infrastructural concern, the controller shouldn't care about the setup of the domain events manager. Yes we can delegate that to a Service and then simply call the Service method. But we can do it better, using Filter Actions.

Simply put, it looks like this

[HandleDomainEvent(typeof(NotifyCommentHandler))]
        public ActionResult AddComment(AddCommentModel model)
        {
            var cmd = Fulldot.FactoryCreate.AddCommentCommand(model, this.GetUserContext(), Request.UserHostAddress);
            this.Handle(cmd);
            return RedirectToRoute("post",new {slug="comments",id=model.PostId});
        }

Just decorate the action with the types fo the handlers. It makes it so easy to add/ remove handlers without cluttering the real controller code and the intention is much clearer.


And this is the HandleDomainEventAttribute

[AttributeUsage(AttributeTargets.Method)]
    public class HandleDomainEventAttribute:ActionFilterAttribute
    {
        private const string ContextKey = "_dispose_handlers";
        private IEnumerable<Type> _handlers;
        public HandleDomainEventAttribute(params Type[] handlers)
        {
            handlers.MustNotBeNull();
            _handlers = handlers;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            List<IDisposable> _res= new List<IDisposable>();
            var events = DependencyResolver.Current.GetService<IDomainEventsManager>();
            foreach(var tp in _handlers)
            {
                var h = DependencyResolver.Current.GetService(tp) as IHandleDomainEvent;
                _res.Add(events.RegisterHandler(h));
            }
            HttpContextRegistry.Set(ContextKey,_res);            
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var disp = HttpContextRegistry.Get<List<IDisposable>>(ContextKey);
            if (disp==null) return;
            disp.ForEach(d=>d.Dispose());

        }
    }

Half of work is done here, the other half is done by the DI Container. Every event handler is registered in the Container (which will take care of all dependencies required) then the attribute just ask for them, registers them to the domain events manager (also supplied by the Container) and after the action is finished, disposes them.

     So for the modify post case  (after which we want both the pingback and the full text search update), the controller action only gets the attribute.

[HandleDomainEvent(typeof(PingbackHandler), typeof(FTSUpdateHandler))]

One line of code, elegant and efficient.

The Generic Repository Is An Anti-Pattern

By Mike on 5 March 2012

It seems to me that when you search about repository pattern, you inevitable stumble upon the generic repository, touted as how a repository should be implemented. Too bad that's a fallacy. A repository is a concept to abstract the access to the persistence, that is not to depend on data access implementation details. There is no formula and no rules.

A repository is also the contract used by the rest of the application to save/load objects.  Every application is different and has different needs of accessing the persistence. And yet , many advise you to use a generic repository like this

public interface IRepository<T>
 {
    IEnumerable<T> GetAll();
    T GetByID(int id);   
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
 }

  One of the touted benefits is the DRY (Don't Repeat Yourself) principle. It's good we don't apply the principle when talking, I mean it would be hard not to repeat the same sounds or words. Sadly, for some it seems that every application has the same persistence access needs, because that's the only scenario where a generic repository makes sense.
 
 I'm aware that a Save , Get or Update method are common in a repository but it depends... . Am I dealing with a query repository or a command one? Is it a repository specialized for reading or for updating model? Because a generic repository can't handle those cases. In one repository you might need GetById and GetByTitle with pagination support. In other you might need only a simple Get method. Other repository might deal only with Save/Update a domain entity.
 
 What I'm trying to say is that the design of a repository interface depends too much on what bounded context it applies for, so there isn't a generic form. If you find that things are repeating it might be a sign of poor architecture or that specific application is really suitable for something generic. But that's a specific case, not the rule.
 
 Other offender in regard to generic repositories is the fact that lots of developers just use it to wrap the DAO (Database Access Object) or an underlying ORM (like EF or Nhibernate). Doing so they add only a useless abstraction, pretty much just making the code more complex with no benefits. A DAO makes it easy to work with a database, an ORM makes it easy to access a database as an OOP virtual storage and to eventually abstract the access to a specific database.
 
 But the repository should abstract the whole persistence layer, hiding implementation details like database engine or what DAO or ORM the app is using but also providing a contract that makes sense from the application point of view. The repository serves the application needs, NOT the database needs.
 
 A generic repository serves the dogma because very few applications have a need for a generic contract applicable everywhere and when used just to mask a DAO, it becomes an unnecessary abstraction. These two reasons make the Generic Repository pattern an anti pattern.

Update: A generic repository fits almost naturally as a domain repository, but only as that. To use it anytime you want a repository and especially when dealing with query repos doesn't make sense.

The Repository Pattern Explained

By Mike on 22 February 2012

Made popular by Domain Driven Design, the Repository pattern is one of my favourite design patterns, which I use almost everywhere. What can I say? I like clear separation between the database access and the rest of the application and this is the purpose of the Repository pattern.

Separation of concerns is something you want in every real-life application and one of the most often met culprits when dealing with bad code is the happy mingleling of the database access  all over the place. Of course, this is also encouraged by the database centric approach which still dominates the developers mindset and you need stronger discipline in order to keep the database access isolated.

In DDD, you start with the domain while the database access , in fact the persistence details, is ironed out at a later time. This means you are free to ignore anything persistence related, but  that doesn't mean that there is no persistence. However the persistence is viewed as a collection of objects where domain object are sent to die... sorry to be persisted and to be retrieved from. Note that the important thing is to consider the repository a collection and not to actually implement a collection (for example .net has an ICollection interface, this has nothing to do with a repository). This approach isn't something specific only to DDD, it can be used in any application as it is a design pattern after all.

In a nutshell, the Repository pattern means abstracting the persistence layer, masking it as a collection. This way the application doesn't care about databases and other persistence details, it only deals with the abstraction (which usually is coded as an interface). The Repository also acts as a facade, simplifying the use of the persistence layer. The application just calls the methods of a repository in order to store or retrieve objects.

Even if you don't do DDD, the objects you send or get from the repositories are the business/domain objects and NOT database related objects. This means that the repository implementation has knowledge of the business objects and knows how to recreate them.

Using the Repository pattern doesn't mean there is only one repository in an application. There can be as many as needed, usually a repository deals with a specific context. For example, an application can have an OrdersRepository, an UsersRepository and an AdminRepository. It is good practice to code against an abstraction, so that's why you'll find many examples dealing with defining a repository interface and not a class. Working against an interface makes it easy to have multiple implementations which helps a lot with testing or changing implementation details.

As an example, let's see how we can apply the pattern for a blog engine. When dealing with posts I can use this 

public interface IPostsRepository
    {
        void Save(Post mypost);
        Post Get(int id);
        PaginatedResult<Post> List(int skip,int pageSize);
        PaginatedResult<Post> SearchByTitle(string title,int skip,int pageSize);
    }

    Post is a domain type, it isn't related to a possible Post class that can be defined in the persistence layer if you're using an OR\M. Remember that the Repository talks with the application only using the types that the application knows about. Any class defined for OR\M usage is hidden in the persistence layer as it's simply an implementation detail.
   
    We see methods for saving a post or for retrieving a post. The Save method is smart enough to detect if it's a new post or a modified post. The PaginatedResult<Post>, is a C# generic type, meaning that the List and SearchByTitle methods return a list of Posts with pagination details.
   
    When testing I can mock or stub this interface, without needing to actually implement a real database access. The application will work only with the interface (which will be injected where is needed), without caring about how things will be actually persisted.
   
    There is no rule or format on how to define a repository. You define it according to what you need from it. But most of the time you'll need to Save or to Get objects in different ways.
   
 A word about using transactions with a repository. Since most of the time the Repository is used in a DDD context, I'll refer to this case.  When you need to execute different operations as a unit, there's where the Unit of Work pattern comes into play. And there are discussion if the UoW is part of the Repository of viceversa. However, in DDD ,the repository should save only Aggregate Roots which themselves are a consistent unit. This means you don't need explicit transaction handling, because saving an aggregate root implicitly means that everything belonging to it is persisted as a transaction.

How I've quit using the Singleton Pattern

By Mike on 16 February 2012

First, let's notice the difference: a singleton is a single instance of a class while Singleton is the name of the design pattern which provides a way to ensure a singleton. Now, that I've cleared this up, I'm using singletons very often but not the Singleton.  And you know how I did it? Without even trying.

Initially I wanted to write a post about when it's appropriate to use Singleton, you know the 'Singleton is evil' story. Some people are not that adamant about it and say that abusing and misusing the pattern makes the Singleton evil. I was one of those people so I wanted to find an example when the pattern can be used without any problem. But looking at my code I've noticed that I haven't use Singleton for a while and it's not because I avoided it. I just didn't need it.

For most of my applications I'm using a dependency injection (DI) container and whenever I need a single instance, I configure the container to serve one instance only. So no need for Singleton there. But what if you don't know/don't want to use a DI container. If you don't know how, it's very useful to learn because you will need it sometime in the future. But if you don't want to, what can you do?

Well, I understand it's a bit overkill to setup a DI container only to manage some singletons, but is the Singleton the solution in those cases? Let's see, the reasons because Singleton is considered evil or an anti pattern (that is a pattern commonly used but with ineffective or even worse results) usually are:
- Breaks the SRP (Single Responsibility Principle) as you have a class managing its own lifecycle .
- Hides dependencies, you won't know that an object needs the Singleton until using the object itself.  This is the same problem when relying to much on static methods or properties of an external object.
- Difficult to test, because a Singleton keeps that state for the entire application (in this case testing), breaking the testing isolation requirement (each test should run independent of other tests).
- It's basically a  global variable, which has no place in a OOP world.

So we have all this reasons for which you don't want to use a Singleton, but once again, what to do if you need a single instance of a class? I've recently coded a small application for personal use. I coded it as fast as I could, didn't care about good OOP or design patterns etc. I still used the Repository pattern because I like to keep separated the persistence logic from the rest of the logic, but that was it. I didn't used a DI container but guess what? I didn't need singletons. And even if I would need one, I'd just create the instance once and store it in a static property of the application.

Truth be told, if you want to do good OOP, any dependency of an object should be either injected via a constructor or passed as a parameter to a method and you simply wouldn't need the Singleton. If you just want to put together fast an application without regard to code quality and maintenance then it doesn't matter if you use the Singleton or any other (anti)pattern. In a way the choice is dictated by the context and by your intentions.