Image Image Image Image Image
Scroll to Top

To Top

AOP Aspect-oriented programming (AOP) is a pragmatic passion that I document here.

Unity Application Block: Event Broker with ASP.NET MVC

For my colleagues at work I evaluated the Simple Event Broker from the Patterns and Practices team. In my opinion this extension is a very valuable piece of software!

To learn more about the Event Broker, you should read:

I made a small sample solution, based on my “WebNoteMvc” project.

The scenario is easy: I want my repositories (or services) to be loosely coupled. In my database foreign references are used. So before I delete data from one repository other repositories should get a notice. The related repositories are now forced to delete their own related data from the DB to keep the data integrity.

My setup of the UnityContainer looks like this:

private static IUnityContainer ContainerSetup()
    IUnityContainer container = new UnityContainer()
        .RegisterType<IWebNote, WebNote>()
        .RegisterTypeForEventBroker<IWebNoteRepository, WebNoteRepository>()
        .RegisterType<IWebNoteCategory, WebNoteCategory>()
        .RegisterTypeForEventBroker<IWebNoteCategoryRepository, WebNoteCategoryRepository>();
    return container;

I introduced a small Extension method called “RegisterTypeForEventBroker“, to make sure that the observers are at least once resolved before the first event. Warning: Your events could be silently ignored, if you forget that extra step! It’s also a good idea to use the repository as a Singleton. (infinite lifetime)

namespace WebNoteMvc.Code.Unity
    using Microsoft.Practices.Unity;
    using Singleton = Microsoft.Practices.Unity.ContainerControlledLifetimeManager;
    /// <summary>
    /// Extention method for IUnityContainer
    /// </summary>
    public static class UnityContainerExtensions
        /// <summary>
        /// Register a type mapping that can be used for the Event Broker Extension
        /// </summary>
        /// <typeparam name="TFrom">System.Type that will be requested.</typeparam>
        /// <typeparam name="TTo">System.Type that will actually be returned.</typeparam>
        /// <param name="container">Container to configure.</param>
        /// <returns>The Microsoft.Practices.Unity.UnityContainer object that this method was called on</returns>
        public static IUnityContainer RegisterTypeForEventBroker<TFrom, TTo>(this IUnityContainer container) where TTo : TFrom
            container.RegisterType<TFrom, TTo>(new Singleton());
            // important: "touch" it, so that we always have a ready instance
            return container;

The preparation of the Publisher as well as the Subscriber is now very easy. You only have to mark your code with the Attributes “Publishes” and “SubscribesTo”:

public event EventHandler NoteBeforeDelete;
public void NoteBeforeDeleteSubscriber(object sender, EventArgs eventArgs) { ... }

Now I’m able to inform other repositories / services that I’m going to delete some data. For my convenience I’m using “EventArgs<T>” and the Extension method “Fire” (both are included in the sources):

this.NoteBeforeDelete.Fire(this, new EventArgs(id));

That’s it. The Event Broker works like a charm. Feel free to test this on your own by deleting some of the provided data:

Download: (1,95 MB) *

I’m planning to write a bit more about „AOP flavored“ stuff from Microsoft. It’s only “flavored”, since it only gives you the feeling of using aspects. In fact no integration into the IL code or proxies are used here.

Tags |


  1. Blogged:… – Unity Application Block: Event Broker with ASP.NET MVC #ccd fb#

  2. Kai

    Hi Johannes,
    first of all, thanks for this great post. I got 2 questions:

    1) Is it possible to apply an aspect to a method of an interface?
    I’m trying to test the event broker in my solution with a mocking framework.

    2) I guess that the events will be handled asynchronous, right?
    So, if you use the event broker for deleting a user including all references, where can you specify the deleting order? (e.g. think about a social plattform: first delete the groups of a user, then delete his comments, then delete his pictures, finally delete the user)

    Best Regards

    • You are welcome! :-)

      The Unity Event Broker Extension doesn’t care about interfaces!
      You will need to write your own stub for that.

      Please also keep in mind that “Publishes” and “SubscribesTo” are giving you the feeling of having an aspect. But this is not the exact case. That’s why I only called it “AOP-flavored”. The Unity Event Broker Extension bases on a simple list if EventHandler Delegates and does not require Microsoft.Practices.Unity.Interception at all.

      Nope. Everything is synchronous. See OnPublisherFiring, it’s just iterates through the list. An asynchronous flow wouldn’t be a smart idea at all, since it complicates everything. (–> could require locking)

      You could hack into the EventBroker to change the list of elements. This shouldn’t be a big problem. But I highly recommend to not doing something like that.

      By requiring an explicit order, you are creating a new (logical) dependency. If you planned the architecture highly-decoupled, the order would not be important.

      If there is still a case where the order is important, than I would do it like the EBC-guys:
      Creating a new module that is receiving the event (eg. „UserBeforeDelete“), and that fires some new events. (eg. „User UserBeforeDeletePriority1“, „UserBeforeDeletePriority2“, „UserBeforeDeletePriority3“).

      By the way: in that example I used a singleton with Unity. This can cause some side effects with the Entity framework. I strictly abandoned all Singletons in any ASP.NET MVC project and replaced them with the PerCallContextLifetimeManager that can be found in the project, too. See for the latest release.

  3. Jonesa

    I like the idea behind it, but I would probably not use it like this. It does not appear as if this tool was made for solving problems like this.

    Having a loosely coupled system is great, but I am not sure whether this is the right approach to make that happen. The repositories can send and receive notifications in order to ensure data integrity. Although one might argue that it is good to have that at an application layer instance (here the repositories rather than a database) I would say ensuring this behavior is easier to test and maintain at one spot, rather than having it distributed to a publish/subscribe pattern. If you want to test the behavior of this implementation systemwide you have to first create substitutes for each repository involved and all their dependencies, whereas with a classical approach it might be suitable to just substitute one single dependency, thus simplifying the test. Yet this depends on your overall design instead.

    As I recommended on tuesday you should have a look into the DDD book. The example taken from the book shows how to solve issues like this (that is: removing invariants of structured object sets) using a so called aggregate.
    An aggregate is a constructed object graph with defined boundaries. The straight boundaries help you to identify methods to construct and maintain the graph. Native to this issue is dealing with the invariants of the system (When you delete a Category, what should happen to the notes in it?) The aggregate root (the starting object) is then responsible for handling requests to the aggregate, orchestrating it all with possibility of delegation.

    The implementation itself is pretty ugly (for my taste), as it is not really type safe. Publishing events using a string name works fine, but you have introduced duplicate code that could easily be overlooked when refactoring. Even resharper does not handle this too well. Loose coupling is great, as long as it does not come with the tradeof of static analysis through your compiler. In a dynamic environment this is a differnt issue.

    As I said, it looks like the Hammer-Nail maxime, where this is a powerful tool used to solve an issue that could be solved in one million more elegant ways. Still, I like this piece of technology and would not like to completely discard the pattern at all. Could you give another example (blogpost) were you definitely have to go for this approach because any other solution is just ugly?

  4. It’s great to see a discussion growing in my blog. This is exactly what I meant with “[…] engaging with, and learning from, other developers”! :-)

    Jones loves Entities. I love POCOS. Two different approaches.

    For the sake of simplicity I implemented the event broker directly in the repository. Fowler would be angry, when seeing something like this. I know that Kais architecture uses a service layers, too. (I think he is referring to our former project from work?!) This would be a better position for the event broker.

    Also for the sake of simplify I showed pure strings. The original article recommended constants. I would put these constants into the assembly that is defining the interfaces. This also helps do discover the (logical) dependencies.

    I clearly see the benefits of DDD. But DDD is not easy to master and definitely not the silver bullet. I would only use it, if I would tackle with complexity given by the domain itself. Adding complexity through DDD to a simple architecture would ruin everything! ^_^

  5. By the way, you asked for another example. My little CRM for the lawyer would be one. At least for me it is proven that the architecture is very simple, easy to understand and maintainable. ^_^

    I am allowed to use the core parts of the little CRM for future clients as long as I completely strip out everything that is in the context of the customers business. (mail sending: public, calculating the offers: prohibited to publish)


    1. The software is basically showing the content of the relational tables. There is no big complexity that requires a syndication of many tables.
    2. Transactions are required. (!= NoSQL)
    3. ASP.NET MVC and Ext.NET are used.


    1. Every “module” has one or more database tables. No module is allowed to access database tables from other modules.
    2. Modules have three assemblies. One with a service and one or more repositories. Another with the interfaces for IoC. And the last one contains the unit tests.
    3. Module interfaces are only exposing stateless objects (POCOS) and primitive types.
    4. Composition of the data can be done in a new module. These special modules have only services, no repositories.
    5. Controllers are directly related to one module. (they are very small)
    6. Much logic is moved directly to the client side by using the Ext.NET framework.
    7. Everything is glued together with Ext.NET controls. Most of them use JSON results. Some like the tab control use iframes (which is ideal here). On most screens you see a syndication of several independent controllers.

    By removing modules from the IoC container and by disabling some Ext.NET controls (they aren’t rendered at all if disabled) through a compiler symbol I can switch between the full and the light version. (cool, isn’t it?!)

    The missing piece is a system to connect these totally independent modules. Here is use the Unity event broker. Until now it works very well for me.

  6. Jones

    I think we are discussing different issues here. I think either you or me have a strange understanding of pocos and entities, at least we are not talking about the same thing.

    For me (that is, for me, as I understand it), a poco is an object that does not follow heavy convention. The distinction of a poco is important when discussing frameworks such as EF or L2S, that are partially generated code files that can follow conventions, enforced by inheritance or meta programming (i.e. attributes).

    A poco is just an object, but one that is controlled by YOU! THE DEVELOPER! rather than by the framework that you are using.I would say an entity can be implemented as a POCO.

    Is it fair to say that you are thinking of a POCO as an object that contains only properties and has no further connections to anything else, so no methods, not attributes, no inheritance? In this case I would see it more as the „Anemic Domain Model“ that Fowler was complaining about and that Ralf Westfal was discussing in his blog.

    Maybe you should clarify your understanding to me because I understand our definitions to be divergent.

    I do not think that DDD adds complexity. DDD for me (update me if I’m wrong) just means to display everything in a natural way. So I agree that it is not a silver bullet but I disagree that it adds complexity.

    Instead, I think the classical Object->Service-Repo-Persistence thought makes things more complicated. The funny thing is, that all of these items are building blocks of ddd. DDD just encourages you to arrange thes building blocks in a natural way.

    Instead of having a customer service to do something for you and pass it a customer, why not have the customer do it directly? By the way, I still do think this classic approach is completely valid and you can create awesome applications with it.

    You are talking about the complexity of the domain itself. If that is high, the classic Lasagna code is very limited because the domain cannot be pressed into the Lasagna pan. Instead, your ONLY way to go is actually DDD, because if you cannot abstract it (lasagna!) you will have to describe it naturally, as close to the domain as possible. This means that DDD does neither add complexity or is complex in itself, but instead is only considered necessary by most people when the lasagna code is at its end.
    So it is treaded as heavy weaponry.

    As I stated I am not opposed to what I called lasagna. Great apps can come from it! I just have seen its limitations. In my company lasagna code just leads to object oriented hungarian notation, that is a billion classes that are called „CustomerRepository, XyzRepository, UvwService“. How is service or repository better than manager, broker, provider or dispatcher?

    For that matter:

    Holy dinosaur, instead of writing these long comments I could feed my own deserted blog XD

Kommentar absenden