INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Email notifications design pattern

Email notifications design pattern

(OP)
Hi,

I have an application where some events trigger email notification to some users. At the moment, the User object contains information of what kind of events he would like to receive. When someone triggers the event (from UI) then the controller action iterates trough all users and sends emails depending on user settings. In all cases the event is a change in my domain model, i.e. object state change or object is created. I think it is something similar to the forum application where user is able to select which thread notifications to receive.

I don't like my current solution because the user must contain separate fields for different types of events. It is not flexible and new type of event would cause in user object change. As well the controller makes a decision who gets a notification and who doesn't. I don't like this approach, it doesn't look right.

What would be the best pattern in this situation? How forum notifications work?

RE: Email notifications design pattern

controllers are entry points, then control what happens and what do do next, they shouldn't control how "it" happens. that would be the responsibility of another component.

the types of triggers you describe sound like things that happen within the domain. therefore I would use the concept of domain events. a common solution I see looks like this

CODE

static class DomainEvents
{
   private static IDomainEventRegistry register
   public static void Register(IDomainEventRegistry register)
   {
      DomainEvents.register = register;
   }

   public static void Handle<T>(T messsage)
   {
      if(register == null)
      {
          throw new InvalidOperationException("domain event registry is not defined.");
      }

      IHandler<T> [] handlers = register.GetHandlersFor<T>();
      handlers.Each(h=>h.Handle(message);
   }
}

interface IHander<T>
{
   void Handle(T message);
}
here is a simple example of how it would work if an event would fire when a customer's address changed.

CODE

class Customer
{
   public void ChangeAddress(Address address)
   {
       var oldAddress = Address.Clone();
       Address = address;

       var message = new CustomerAddressChanged(this, oldAddress);
       DomainEvents.Handle(message);

   }
}
and the handler may look like this

CODE

class SendEmail : IHandler<CustomerAddressChanged>
{
   SendEmail(IEmailer emailer)
   {
     this.emailer = emailer
   }

   public void Handle(CustomerAddressChanged message)
   {
       var customer = message.Customer;
       var previous = message.OldAddress;
       var body = BuildEmailMessageFrom(customer, previous);

       emailer.Send(customer.Email, "You're address has changed", body);
   }
}

class Audit : IHandler<CustomerAddressChanged>
{
   public void Handle(CustomerAddressChanged message)
   {
       var customer = message.Customer;
       var previous = message.OldAddress;

       //create an audit entry to keep a history of critical changes.
   }
}
this is most elaborate approach to solving the problem of domain driven events. something like sending emails for a forum thread is much simpler.

just associate a collection of users (or email addresses) with each thread. when a thread is changed, send emails to each user/email.

CODE

class Thread
{
   private ICollection<Post> posts = new List<Post>();
   private ICollection<User> users = new List<Users>();

   public Thread(User user, Post original)
   {
      Creator  = user;

      original.Thread = this;
      posts.Add(original);

      ReceiveNotifications(Creator);
   }

   public IEnumerable<Post> Posts{get {return posts;}}
   public User Creator {get; private set;}

   public void Respond(Post post, INotification notification)
   {
      post.Thread = this;
      posts.Add(post);

      ReceiveNotifications(post.Author);

      users.Each(notification.Notify);
   }

   public void ReceiveNotifications(User user)
   {
      if(users.Contains(user)) return;
      users.Add(user);
   }
}
I hope this helps provide some insight into how the problem could be solved.

Jason Meckley
Programmer

FAQ855-7190: Database Connection Management
FAQ732-7259: Keeping the UI responsive

RE: Email notifications design pattern

(OP)
Thanks Jason,

Very interesting code, it surely gave me something to think about.

One question, just to be sure, does the registration of handlers should happen on every starup of the application? I mean, it is not persisted any how?

RE: Email notifications design pattern

that would depend on how to implement IDomainEventRegistry. I use an IoC container. in that instance I register the handler type in the container and resolve an instance at the time I need it.

My IoC of choice is Castle Windsor the code would look like this

CODE

class DomainEventsFacility : Abstract Facility
{
  public void Init()
  {
      Kernel
            .Register(AllTypes
                  .FromAssembly(GetType().Assembly)
                  .BasedOn(typeof(IHandler<>))
                  .Configure(c=>c.Named(c.Implementation.Name).LifeStyle.Trasient)
                  .WithService.FirstInterface());
            .Register(Component
                  .For<IDomainEventsRegistry>()
                  .AsFactory()
                  .LifeStyle.Singleton);

      var registry = Kernel.Resolve<IDomainEventsRegistry>();
      DomainEvents.Register();
  }
}
I would also adjust the DomainEvents fascade slightly, to account for how Castle manages resolution.

CODE

static class DomainEvents
{
   private static IDomainEventRegistry register
   public static void Register(IDomainEventRegistry register)
   {
      DomainEvents.register = register;
   }

   public static void Handle<T>(T messsage)
   {
      if(register == null)
      {
          throw new InvalidOperationException("domain event registry is not defined.");
      }

      register
          .GetHandlersFor<T>()
          .Each(h => {
              try
              {
                 h.Handle(message);
              }
              finally
              {
                 register.Release(h);
              }
          });
   }
}

interface IDomainEventRegistry
{
   IHandler<T>[] GetHandlersFor<T>();
   void Release(IHandler<T> handler);
}
If you are not using an IoC container, then you would need to inform the registry of either instances of all the handlers, or how to resolve the handlers.

Jason Meckley
Programmer

FAQ855-7190: Database Connection Management
FAQ732-7259: Keeping the UI responsive

RE: Email notifications design pattern

Is this not an Observer style idea?

C

RE: Email notifications design pattern

probably a combination of concepts. the first pattern that comes to mind is the command pattern. I typically relate the observer pattern to the UI and the event keyword (.net).

I guess you could define it as such. the registry in the observer, containing a collection of notifiers. in this instance the implementation details are contained in the IoC container itself.

I think an event broker demonstrates the concept of observer in a more explicit manner at the infrastructure layer.

Jason Meckley
Programmer

FAQ855-7190: Database Connection Management
FAQ732-7259: Keeping the UI responsive

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close