Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Email notifications design pattern

Status
Not open for further replies.

Audriusa83

Programmer
Jul 5, 2010
4
0
0
GB
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?
 
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
faq732-7259
 
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?
 
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
faq732-7259
 
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
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top