Monthly Archives: May 2012

When to throw exceptions

I’ve written several posts about exceptions. For instance when you should catch them or how you should design them. In this post I’ll discuss when you should throw exceptions.

Exceptions are thrown when something exceptional have happended. But what does that mean? In fact it’s really simple. Let’s look at an example interface:

interface IUserRepository
{
	void Save(User user);
}

You should throw an exception every time that method fails to save the user into the data source. The failure reason do really not matter. All of these reasons are valid:

  • The user object do not contain all mandatory information
  • The user object is null
  • The data source is off line
  • The data source rejected the save.

Why? Because the method is named Save and returns void. That is, the contract of the method indicates that a save should in most cases be successful. Hence something exceptional have happened if the user is not saved into the data source.

But couldn’t you have written something like this instead:

interface IUserRepository
{
	bool Save(User user);
}

Yes, sure. That method would return false instead of throwing exceptions. But the method contract indicates that the method can fail as many times that it can succeed. You really do not mean that, do you?

but.. but… The Remove method usually returns a bool.

interface IUserRepository
{
	bool Remove(User user);
}

Yes. It do. The reason to that is that it says that it’s OK to call Remove even if the user do not exist. imho it’s a vague contract. It’s not clear if the method means that the removal is expected to fail or if the method allows you to remove non-existing items. I would have used void as return value instead.

Myth: Exceptions are expensive

First of all: Exceptions that are not thrown are not expensive.

And if you start to think about it, exceptions are actually a lot cheaper than using return values. Exceptions forces you to take action, no action means that your application crashes. The exceptions also include the exact location of the error. Return values only work if you check and handle all of them. I would like to see any reasonable sized application which uses return values where all of them are handled.

The point is that it’s a lot more tedious task to find and fix bugs in applications that uses return values instead of exceptions since you have to use details logs or reproduce errors to be able to locate and fix them. The amount of time spend to locate and correct errors probably costs a lot more money than buying new hardware to make up for the exception performance penalty.

Summary

Throw exceptions if the method contract is violated.



Griffin.Container – “The drunken IoC container”

(I started writing this blog entry at friday night, but somehow I didn’t manage to finish it.)

My son has just fallen asleep and wifey is working. Which means that I got a friday night all by myself. So I’ve put some beer and Bacardi Breezers (kinda girly, I know. But I can’t help myself) in a nice row on my desk. Instead of continuing to code on my next entrepenural endeavor I’ve decided to do something fun and challenging. And that is to code an inversion of control container in three hours (until the boss get’s home). (It took another two hours today to clean up the nonsense in this blog entry)

It’s my third attempt during the last couple of years. My both last attempts was just a bit of fooling around and this time I’ve decided to try to create a lean killing machine. So I’ve come up with a slightly different approach compared to my last attempts.

The responsibility

In my eyes an IoC container has three responsibilites. Hence I’ve divided the container into three different classes.

Registration

A container got to be able to register the services that should be provided. I hate those XML configurations since it’s hard to discover configuration errors. I also cry when I have to use API’s which heavily uses extensions methods, since the intellisense for them is messy and hard to understand.

I’ve therefore created three types of registration options:

The attribute

Registration through attributes. Works quite nicely. Create a class and add the [Component] attribute on it. Repeat for all classes in all of your assemblies.

[Component]
public class MyClass : IService
{
}

Control the lifetime:

[Component(Lifetime = Lifetime.Singleton)]
public class MyClass : IService
{
}

And register everything using:

registrar.RegisterComponents(HostingEnvironment.MapPath("~/bin"), "*.dll));

Done.

The module

You can also control the registration process through modules. Great since each module/namespace/section can itself decide what should be registered in the container.

public class UserManagementModule : IContainerModule
{
    public void Register(IContainerRegistrar registrar)
    {
        registrar.Register<UserService>();
    }
}

Then just load all modules:

// can also specify path + filepattenr as the example above.
registrar.RegisterModules(Assembly.GetExecutingAssembly());

The traditional approach

There are also the traditional RegisterXxxxx methods.

public interface IContainerRegistrar
	IEnumerable<ComponentRegistration> Registrations { get; }

	void RegisterComponents(Lifetime defaultLifetime, string path, string filePattern);
	void RegisterComponents(Lifetime defaultLifetime, params Assembly[] assemblies);

	void RegisterModules(string path, string filePattern);
	void RegisterModules(params Assembly[] assemblies);

	void RegisterConcrete<TConcrete>(Lifetime lifetime = Lifetime.Scoped) where TConcrete : class;
	void RegisterConcrete(Type concrete, Lifetime lifetime = Lifetime.Scoped);

	void RegisterService<TService>(Func<IServiceLocator, object> factory, Lifetime lifetime = Lifetime.Scoped);
	void RegisterService(Type service, Func<IServiceLocator, object> factory, Lifetime lifetime = Lifetime.Scoped);

	void RegisterType<TConcrete, TService>(Lifetime lifetime = Lifetime.Scoped)
		where TService : class
		where TConcrete : class;
	void RegisterType(Type concrete, Type service, Lifetime lifetime = Lifetime.Scoped);

	void RegisterInstance<TService>(TService instance) where TService : class;
	void RegisterInstance(Type service, object concrete);
}

The build plan

Performance is important. And you can’t get performance if you do not analyze how each service should be built (before the actual service location). I therefore go through all classes, check their dependencies and create a plan for how they should be built. I then analyze which classes is used by which services and create a mapping between each service and the implementing classes.

The builder supports multiple constructors. It uses the most specific constructor for which it can resolve all dependencies for.

/// <summary>
/// Used to build the container.
/// </summary>
public interface IContainerBuilder
{
    /// <summary>
    /// Builds a container using the specified registrations.
    /// </summary>
    /// <param name="registrar">Registrations to use</param>
    /// <returns>A created container.</returns>
    IParentContainer Build(IContainerRegistrar registrar);
}

Service location

The container itself IS implementing the service location pattern. Hence the container interface is really a service location interface and we’ll use that as our base.

public interface IServiceLocator
{
    bool IsRegistered(Type type);
    T Resolve<T>() where T : class;
    object Resolve(Type service);
    IEnumerable<T> ResolveAll<T>() where T : class;
    IEnumerable<object> ResolveAll(Type service);
}

The container itself have been divided into two containers. A parent container which is the one generated by the builder and a scoped container.

public interface IParentContainer : IServiceLocator
{
    IChildContainer CreateChildContainer();
}

public interface IChildContainer : IServiceLocator, IDisposable
{
    
}

Scoped services can only be resolved by a scoped container. So you got to use something like this:

using (var scoped = container.CreateChildContainer())
{
    // All scoped services which is resovled here
    // will be disposed automatically.
}

That should make it easier to handle scoping in WCF, MVC3 and similar frameworks.

Extension points

The divided architecture allows you to customize the container quite nicely.

Custom registration

  • Inherit ContainerRegistrar and override Add to be able to handle all registrations.
  • Override CreateRegistration to control which interfaces a class can implement
  • Pass a custom IServiceFilter class to the ContainerRegistrar to filter out which service all classes can be registered for.

Building

  • Inherit ContainerBuilder and override TryGetConstructor to be able to control which constructor the builder should use.

Service location

  • Inherit Container and ChildContainer and override the GetInstance method to get full control over the returned instances. Perfect approach if you want to generate proxies or use AOP.

Usage

public class IntegrationTests
{
    [Fact]
    public void SimpleRegistrationTransient()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<MySelf>(Lifetime.Transient);
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        var instance1 = container.Resolve<MySelf>();
        var instance2 = container.Resolve<MySelf>();

        Assert.NotSame(instance1, instance2);
    }


    [Fact]
    public void OneDependencySingleton()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<MySelf>(Lifetime.Transient);
        registrar.RegisterType<OneDepencency>(Lifetime.Singleton);
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        var instance1 = container.Resolve<OneDepencency>();
        var instance2 = container.Resolve<OneDepencency>();

        Assert.Same(instance1, instance2);
    }

    [Fact]
    public void ResolveAllStartable()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<Startable1>(Lifetime.Singleton);
        registrar.RegisterType<Startable2>(Lifetime.Singleton);
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        var instances = container.ResolveAll<ISingletonStartable>();

        Assert.Equal(2, instances.Count());
    }

    [Fact]
    public void ResolveFromComponents()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterComponents(Lifetime.Singleton, Assembly.GetExecutingAssembly());
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        container.Resolve<OneDepencency>();
    }

    [Fact]
    public void ResolveFromModules()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterModules(Assembly.GetExecutingAssembly());
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        container.Resolve<MySelf>();
    }

    [Fact]
    public void ChildContainer()
    {
        var registrar = new ContainerRegistrar();
        registrar.RegisterType<MySelf>();
        var builder = new ContainerBuilder();
        var container = builder.Build(registrar);

        MySelf instance;
        using (var childContainer = container.CreateChildContainer())
        {
            instance = childContainer.Resolve<MySelf>();
        }

        Assert.True(instance.IsDisposed);
    }
}

Performance

I used the benchmark testing code which have been created by Daniel Palme.

Name                    Singleton       Transient       Combined        #.ctor Singleton        #.ctor Transient        #.ctor Combined
No                      30              37              45              1                       2000001                         1000000
AutoFac                 582             2635            6225            1                       2000001                         1000000
Dynamo                  65              66              113             1                       2000001                         1000000
Funq                    74              87              231             1                       2000001                         1000000
Hiro                    104             99              109             1                       2000001                         1000000
LightInject             92              90              98              1                       2000001                         1000000
Munq                    91              108             342             1                       2000001                         1000000
Petite                  67              70              210             1                       2000001                         1000000
SimpleInjector          71              81              101             1                       2000003                         1000001
StructureMap            925             1032            3318            1                       2000001                         1000000
Unity                   1346            1694            5599            1                       2000001                         1000000
Windsor                 486             2102            6324            1                       2000001                         1000000
Griffin.Container       158             183             471             1                       2000001                         1000000

Chart:

(I had to remove ninject & spring.net from the chart since they are way too slow)

The performance is OK by me since I’ve not done any optimizations yet.

Summary

I’m quite satisfied with the result and a bit suprised that I managed to create the architecture that I did last night. It was really fun and I think that I’ll continue to improve the container so it becomes even more useful.


SOLID principles with real world examples

The following article aims to explain the five SOLID principles with real world examples. The SOLID principles are five programming principles which is considered to be the foundation of every well designed application. Following the principles will most likely lead to applications which are is easy to extend and maintain. That’s possible since you got small well defined classes with clear contracts.

All motivator images are created by Derick Baley.

Let’s get started with the principles.

Single Responsibility Principle

Single responsibility states that every class should only have one reason to change. A typical example is an user management class. When you for instance create a new user you’ll most likely send an welcome email. That’s two reasons to change: To do something with the account management and to change the emailing procedure. A better way would be to generate some kind of event from the account management class which is subscribed by a UserEmailService that does the actual email handling.

The most effective way to break applications it to create GOD classes. That is classes that keeps track of a lot of information and have several responsibilities. One code change will most likely affect other parts of the class and therefore indirectly all other classes that uses it. That in turn leads to an even bigger maintenance mess since no one dares to do any changes other than adding new functionality to it.

Making sure that a class has a single responsibility makes it per default also easier to see what it does and how you can extend/improve it.

Classes that are hard to unit test are often breaking SRP.

External links

* Wikipedia
* Example & tips on how to follow the principle (earlier post by me)

Open/Closed principle

Open/Closed principle says that a class should be open for extension but closed for modification. Which means that you can add new features through inheritance but should not change the existing classes (other than bug fixes).

The reason is that if you modify a class, you’ll likely break the API/Contract of the class which means that the classes that depend on it might fail when you do so. If you instead inherit the class to add new features, the base contract is untouched and it’s unlikely that dependent classes will fail.

Example violation

Here is a real world parser method (from a SO question which I’ve answered):

    public void Parse()
    {
        StringReader reader = new StringReader(scriptTextToProcess);
        StringBuilder scope = new StringBuilder();
        string line = reader.ReadLine();
        while (line != null)
        {
            switch (line[0])
            {
                case '$':
                    // Process the entire "line" as a variable, 
                    // i.e. add it to a collection of KeyValuePair.
                    AddToVariables(line);
                    break;
                case '!':
                    // Depending of what comes after the '!' character, 
                    // process the entire "scope" and/or the command in "line".
                    if (line == "!execute")
                        ExecuteScope(scope);
                    else if (line.StartsWith("!custom_command"))
                        RunCustomCommand(line, scope);
                    else if (line == "!single_line_directive")
                        ProcessDirective(line);
    
                    scope = new StringBuilder();
                    break;
    
                default:
                    // No processing directive, i.e. add the "line" 
                    // to the current scope.
                    scope.Append(line);
                    break;
            }
    
            line = reader.ReadLine();
        }
    }

It works great. But the method have to be changed each time we want to add support for a new directive. It’s therefore not closed for modification.

Solution

Lets create an interface which is used for each handler (for '$' and '!' in the example above):

    public interface IMyHandler
    {
        void Process(IProcessContext context, string line);
    }

Notice that we include a context object. This is quite important. If we create a new parser called SuperCoolParser in the future we can let it create and pass a SuperAwsomeContext to all handlers. New handlers which supports that context can use it while others stick with the basic implementation.

We comply with Liskovs Substitution Principle and doesn’t have to change the IMyHandler.Process signature (and therefore keeping it closed for modification) when we add new features later on.

The parser itself is implemented as:

    public class Parser
    {
        private Dictionary<char, IMyHandler> _handlers = new Dictionary<char, IMyHandler>();
        private IMyHandler _defaultHandler;
    
        public void Add(char controlCharacter, IMyHandler handler)
        {
            _handlers.Add(controlCharacter, handler);
        }
    
        private void Parse(TextReader reader)
        {
            StringBuilder scope = new StringBuilder();
            IProcessContext context = null; // create your context here.
    
            string line = reader.ReadLine();
            while (line != null)
            {
                IMyHandler handler = null;
                if (!_handlers.TryGetValue(line[0], out handler))
                    handler = _defaultHandler;
    
                handler.Process(context, line);
    
    
                line = reader.ReadLine();
            }
        }
    }

If you go back and look at the ! handling you’ll see a lot of if statements. That method likely have to be changed to add support for more features. Hence it do also violate the principle. Let’s refactor again.

    public interface ICommandHandler
    {
        void Handle(ICommandContext context, string commandName, string[] arguments);
    }
    
    public class CommandService : IMyHandler
    {
        public void Add(string commandName, ICommandHandler handler) 
        {
        }
    
        public void Handle(IProcessContext context, string line)
        {
           // first word on the line is the command, all other words are arguments.
           // split the string properly
    
           // then find the corrext command handler and invoke it.
           // take the result and add it to the `IProcessContext`
        }
    }

External links

* Wikipedia

Liskovs Substitution Principle

Liskovs Substitution Principle states that any method that takes class X as a parameter must be able to work with any subclasses of X.

The principle makes sure that every class follows the contract defined by its parent class. If the class Car has a method called Break it’s vital that all subclasses breaks when the Break method is invoked. Imagine the suprise if Break() in a Ferrari only works if the switch ChickenMode is activated.

Violation

Let’s use the motivator image as inspiration and define the following classes:

    public interface IDuck
    {
       void Swim();
    }
    public class Duck : IDuck
    {
       public void Swim()
       {
          //do something to swim
       }
    }
    public class ElectricDuck : IDuck
    {
       public void Swim()
       {
          if (!IsTurnedOn)
            return;
    
          //swim logic  
       }
    }

And the calling code:

    void MakeDuckSwim(IDuck duck)
    {
        duck.Swim();
    }

As you can see, there are two examples of ducks. One regular duck and one electric duck.

The electric duck can only swim if it’s turned on.The MakeDuckSwim method will not work if a duck is electric and not turned on.

That breaks LSP since any user of the IDuck interface expects the duck to swim when calling MakeDuckSwim.

Solution

You can of course solve it by doing something like this (in the method that uses the ducks)

    void MakeDuckSwim(IDuck duck)
    {
        if (duck is ElectricDuck)
            ((ElectricDuck)duck).TurnOn();
        duck.Swim();
    }

But that would break Open/Closed principle and has to be implemented everywhere that the ducks are used (and therefore still generate instable code).

The proper solution would be to automatically turn on the duck in the Swim method and by doing so make the electric duck behave exactly as defined by the IDuck interface.

    public class ElectricDuck : IDuck
    {
       public void Swim()
       {
          if (!IsTurnedOn)
            TurnOnDuck();
    
          //swim logic  
       }
    }

External links

* Wikipedia

Interface Segregation Principle

ISP states that interfaces that have become “fat” (like god classes) should be split into several interfaces. Large interfaces makes it harder to extend smaller parts of the system.

There is nothing that says that there should be a one-to-one mapping between classes and interfaces. It’s in fact much better if you can create several smaller interfaces instead (depends on the class though).

Violation

The MembershipProvider in ASP.NET is a classical example of a violation. MSDN contains a large article (which 4 out of 34 have found useful) which contains a long and detailed instruction on how to properly implement the class.

Solution

The provider could have been divided in several parts:

* MembershipProvider – A facade to the below interfaces
* IAccountRepository – Used to fetch/load accounts
* IPasswordValidator – Checks that the password is valid (according to business rules)
* IPasswordStrategy – How to store PW (hash it, use encryption or just store it in plain text)

Now you only have to implement a small part if you need to customize the provider (for instance IAccountRepository if you are using a custom data source). There’s a saying: “Favor composition over inheritance” which the membership providers illustrates well. The original solution used inheritance while mine used composition.

External Links

* Wikipedia

Dependency Inversion Principle

The principle which is easiest to understand. DIP states that you should let the caller create the dependencies instead of letting the class itself create the dependencies. Hence inverting the dependency control (from letting the class control them to letting the caller control them).

Before

    public class Volvo
    {
        B20 _engine;

        public Volvo()
        {
           _engine = new B20();
        }
    }

After

    public class Volvo
    {
        IEngine _engine;

        public Volvo(IEngine engine)
        {
           if (engine == null) throw new ArgumentNullException("engine");
           _engine = engine;
        }
    }

Which makes it a lot more fun since we now can do the following:

    var myVolvo = new Volvo(new BigBadV12());

(Nice real world example, huh? ;))

Update

I messed up a bit. Dependency Inversion states that you should depend upon abstractions and that lower layers should not be aware of higher layers. I’ll get back to that. Dependency Injection is when you inject dependencies into the constructors instead of creating them in the class. Inversion Of Control is that the container controls your objects and their lifetime.

A. HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
B. ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS

The original principle targets modules while I also like to apply it at class level too. It makes the principle easier to apply (so the text below is how I apply the principle).

Depend on abstractions simply means that you should depend on as generic class/interface as possible. For instance IUserRepository instead of DbUserRepository or HttpRequestBase instead of HttpRequest. The purpose is that your code should be as flexible as possible. The more abstract the dependencies are, the easier it is to refactor them or create new implementations.

Depending on abstractions also make your code less likely to change if the dependency change.

External links

* Wikipedia
* Introduction

Summary

Feel free to leave a comment if something is unclear. It will not just help you, but all future readers.


Liskovs Substitution Violation in the real world

I was creating an integration between my own users table (or document since I use RavenDB) with the membershipprovider in ASP.NET. I’m using the default SQL provider.

When doing so I noticed that my code was failing all the time in the register action in the account controller (ASP.NET MVC3). The error message saying “An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator“.

var user = _userRepository.Create(model.UserName, model.Email, model.DisplayName);
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, user.Id, out createStatus);

User.Id is a string. I took a look at the createStatus which is returned from CreateUser and it said InvalidProviderUserKey. MSDN did not help to discover why the error was returned (no indication for the enum value nor in the CreateUser documentation).

So I started to google after implementations of the SqlMembershipProvider. The first one that I found was the one in Mono. It had the following logic:

if (providerUserKey != null && ! (providerUserKey is Guid)) {
    status = MembershipCreateStatus.InvalidProviderUserKey;
    return null;
}

Why the (s)hell did they do that?” was my first though. A clear violation of LSP since the contract says object and all they support is a simple Guid. Come on. At least support string.

So I started to search for the MS implementation and found the sample provider in MSDN: http://msdn.microsoft.com/en-us/library/6tc47t75.aspx

So the design decision was Microsofts own. Next time, please document “features” like that.


Griffin.Networking – A somewhat performant networking library for .NET

Disclaimer: The current framework release is a beta. It should be reasonable stable, but don’t blame me if it blow up your computer.

Introduction

Griffin.Networking is a networking library written in C# which purpose is to:

a) abstract away the repetitive tasks which you have to do with vanilla .NET
b) Create a more structured way of processing the inbound and outbound data

Those two goals should lower the time it takes to develop networking applications and also improve the performance thanks to a (hopefully) well-designed networking layer.

The framework also have Inversion Of Control support built in from start (be careful, slow containers hurt performance a lot). The IoC support is provided by a service location interface (which should not be exposed outside the framework).

The goal with this article is to describe the framework and show you have to develop an application with it. You will have a working JSON RPC implementation (server side) when done. The client side can be quite easily created afterwards. Simply create a RequestEncoder and a ResponseDecoder for the framework, everything else can be reused from the server implementation.

Background

I’ve built several networking applications in the past. Everything from small client applications in C# to performant socket servers in C++ utilizing IO Completion Ports.

They have worked well, but I always seemed to repeat myself when implementing my applications. The biggest problem is that it’s hard to get an extendable architecture where you can inject handlers into the protocol handling. My C# WebServer (Google “C# webserver” and click on the first search result) illustrates this well. It’s not easy to follow the communication flow.

I did therefore decide to try create a networking library which is easy to use and extend. During my research I stumpled upon Netty for Java which my library is heavliy inspired by.

Architecture

The purpose of this section is to give you a brief overview over the architecture and the terms which will be used throughout the article. Some things in this section may not make sense until you have read the entire article.

Channel

The channel is the IO layer. In most cases it’s a socket implementation, but could be anything used for communication. The default socket implementation uses the classical Begin/End type of methods. They will probably be replaced by the new Async methods later on.

There are two types of channels. Server channels who’s responsibility is to accept new connections and build the correct client channel (and it’s pipeline). Client channels which responsibility is to send and receive information from the remote peer.

    public interface IChannel
    {
        void HandleDownstream(IPipelineMessage message);
    }

As you can see, the channel interface is quite small. The reason to this is that the entire framework is asynchronous. All communication is made by messages. The contract of a channel says that is should only be able to receive and process messages. A message (read more below) can for instance be Connect, SendBuffer or Close. All channel implementations takes a pipeline (see below) in the constructor and use it to send messages to your application.

Pipeline

The pipeline is the most central part of the library. All the action happens in the pipeline. It’s in the pipeline that you authorize the users, transform the incoming byte[] array into something more usable like a HttpRequest etc etc.

The pipeline has two directions (compare with a road with two lanes). The lane from the channel to the application is called upstream, since the message travels up from the channel to your application. The other direction is called downstream since the message travels down to the channel.

A pipeline can contain an arbitrary number of handlers, and each direction have it’s unique set of handlers. A HTTP streaming server might only contain the HttpHeaderDecoder in the upstream and a HttpFileStreamer in the downstream to gain performance, while a complete HttpServer would include session management, authentication, logging, error handler etc as upstream handlers.

public interface IPipeline
{
	/// <summary>
	/// Send something from the channel to all handlers.
	/// </summary>
	/// <param name="message">Message to send to the client</param>
	void SendUpstream(IPipelineMessage message);

	/// <summary>
	/// Set down stream end point
	/// </summary>
	/// <param name="channel">channel which will handle all down stream messages</param>
	void SetChannel(IChannel channel);

	/// <summary>
	/// Send a message from the client and downwards.
	/// </summary>
	/// <param name="message">Message to send to the channel</param>
	void SendDownstream(IPipelineMessage message);
}

The architecture allows you to have full control over how the incoming and outgoing data is processed before it arrives in your application or in the channel.

Messages

As mentioned in the previous section, the pipeline are used to send message to/from your application. These messages are small classes which contains the information to process. a message can be compared with the EventArg classes in the .NET event mechanism. POCO classes which implements the IPipelineMessage interface.

Messages that requires actions should be named as verbs (Send) while event messages should be named past tense (Received).

The general guideline is that each message may only contain one type of information. You may not have a message called Received with an object property which is a byte[] in the beginning and a SuperDeluxeObject in the end. Rather create a new message named ReceivedSuperDeluxe which contains the SuperDeluxeObject object. It makes the processing cleaner and easier to follow.

Example message:

public class Connect : IPipelineMessage
{
    private readonly EndPoint _remoteEndPoint;

    public Connect(EndPoint remoteEndPoint)
    {
        if (remoteEndPoint == null)
            throw new ArgumentNullException("remoteEndPoint");

        _remoteEndPoint = remoteEndPoint;
    }

    public EndPoint RemoteEndPoint
    {
        get { return _remoteEndPoint; }
    }
} 

Pipeline handlers

Pipeline handlers are used to process the messages which are sent through the pipeline. They can either be singletons (shared among channels) or be created per channel. Handlers that are constructed together with the pipeline can store state information since they are used by one channel only.

Example upstream handler which traces the received information:

public class BufferTracer : IUpstreamHandler
{
    private readonly ILogger _logger = LogManager.GetLogger<BufferTracer>();

    public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
    {
        var msg = message as Received;
        if (msg != null)
        {
            var str = Encoding.UTF8.GetString(msg.BufferSlice.Buffer, msg.BufferSlice.Position, msg.BufferSlice.RemainingLength);
            _logger.Trace(str);
        }

        context.SendUpstream(message);
    }
}

Notice how it sends all messages to the next handler using context.SendUpstream(message). This is quite important. Each handler get to decide whether the message should be propagated up the call stack or not. It’s also how messages are transformed into something more usable. Let’s look at the HTTP HeaderDecoder handler.

public class HeaderDecoder : IUpstreamHandler
{
    private readonly IHttpParser _parser;
    private int _bodyBytesLeft = 0;

    public HeaderDecoder(IHttpParser parser)
    {
        if (parser == null) throw new ArgumentNullException("parser");
        _parser = parser;
    }

    public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
    {
        if (message is Closed)
        {
            _bodyBytesLeft = 0;
            _parser.Reset();
        }
        else if (message is Received)
        {
            var msg = (Received) message;

            // complete the body
            if (_bodyBytesLeft > 0)
            {
                _bodyBytesLeft -= msg.BufferSlice.Count;
                context.SendUpstream(message);
                return;
            }

            var httpMsg = _parser.Parse(msg.BufferSlice);
            if (httpMsg != null)
            {
                var recivedHttpMsg = new ReceivedHttpRequest((IRequest) httpMsg);
                _bodyBytesLeft = recivedHttpMsg.HttpRequest.ContentLength;
                _parser.Reset();

                // send up the message to let someone else handle the body
                context.SendUpstream(recivedHttpMsg);
                msg.BytesHandled = msg.BufferSlice.Count;
                context.SendUpstream(msg);
            }

            return;
        }

        context.SendUpstream(message);
    }
} 

Two things are important here:

It follows Single Responsibility Principle

It doesn’t actually parse the HTTP message but uses an external parser for that. It’s easy to follow what the handler does since it does not violate Single Responsibility Principle, and we can at any time switch parser if we find a more performant one.

It transforms the Received message into a ReceivedHttpRequest

All messages should be considered to be immutable. Don’t change their contents unless you have a really good reason to. Don’t propagate the original package upstream, but create a new message instead.

Switching sides

A pipeline handler can at any time switch from the downstream to the upstream (or vice versa). Switching sides will always invoke the first handler in the other side. This allows us to stream line the process and to avoid confusion.

public class AuthenticationHandler : IUpstreamHandler
{
	private readonly IAuthenticator _authenticator;
	private readonly IPrincipalFactory _principalFactory;

	public AuthenticationHandler(IAuthenticator authenticator, IPrincipalFactory principalFactory)
	{
		_authenticator = authenticator;
		_principalFactory = principalFactory;
	}

	public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		var msg = message as ReceivedHttpRequest;
		if (msg == null)
		{
			context.SendUpstream(message);
			return;
		}

		var authHeader = msg.HttpRequest.Headers["Authorization"];
		if (authHeader == null)
		{
			context.SendUpstream(message);
			return;
		}

		var user = _authenticator.Authenticate(msg.HttpRequest);
		if (user == null)
		{
			//Not authenticated, send error downstream and abort handling
			var response = msg.HttpRequest.CreateResponse(HttpStatusCode.Unauthorized,													   "Invalid username or password.");
			context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
		}
		else
		{
			var principal =
				_principalFactory.Create(new PrincipalFactoryContext {Request = msg.HttpRequest, User = user});
			Thread.CurrentPrincipal = principal;
		}
	}
}

Pipeline factories

A pipeline (and all of it’s handlers) needs to be constructed each time a new channel is created. There are two built in factories in the framework.

One that uses an interface called IServiceLocator which allows you to add support for your favorite IoC container. And one that uses delegates to created stateful handlers.

var factory = new DelegatePipelineFactory();
factory.AddDownstreamHandler(() => new ResponseEncoder());

factory.AddUpstreamHandler(() => new HeaderDecoder(new HttpParser()));
factory.AddUpstreamHandler(new HttpErrorHandler(new SimpleErrorFormatter())); //singleton
factory.AddUpstreamHandler(() => new BodyDecoder(new CompositeBodyDecoder(), 65535, 6000000));
factory.AddUpstreamHandler(() => new FileHandler());
factory.AddUpstreamHandler(() => new MessageHandler());
factory.AddUpstreamHandler(new PipelineFailureHandler()); //singleton

Buffers

A fundamental part of a performant networking library is how the data is handled. All larger allocations hurt performance. We don’t want to create a new byte[65535] each time we read or send a new packet. It takes time to do the allocation, the garbage collector have to work more and the memory will end up fragmented.

The framework solves this by using buffer pools and a class called BufferSlice. We can allocate a buffer which is 5Mb large and slice it into smaller pieces which we use in the processing. We can either make the buffer pool a singleton or let each handler allocate it’s own buffer pool (it’s still just five allocations instead of 5000 if you have five handlers).

The BufferSlice class returns it’s buffer to the pool when it’s disposed. It’s therefore important that all messages that uses the BufferSlice class implements IDisposable, since the channel will dispose all messages when it’s done with them.

Performance

The framework is still quite new (abut one month =)). The performance is not at it’s peak yet.

However, I’ve used Apache’s ab tool to throw 5000 requests at the HTTP listener. The framework handled about 280 HTTP requests per second (localhost) which I consider to be OK this early in the project. The memory consumption was about 80Mb (working set). (Note that the numbers doesn’t really say anything.) Feel free to help improve the performance or do your own benchmarks. I would like to get a sample application which I can use for performance tuning (and compare the performance with other frameworks).

Building a JSON RPC server

It’s time to start building a JSON RPC server. Create a new console application name something like JsonRpcServer. Start the nuget package console and run install-packate griffin.networking to install the framework.

The specification for JSON RPC can be found at the official website. This article will not help you understand it, but only showing how you can implement it. The specification do not say anything about how the messages are transferred and we’ll therefore create a simple envelope which will be used to wrap the messages. The envelope is a simple binary header with a version (byte) and a length (int) field.

Decoding / Encoding

The first thing we need to do is to process the incoming bytes. We have to decode them into something that we can work with. As mentioned we’ll use a simple envelope. Something like:

public class SimpleHeader
{
	public int Length { get; set; }
	public byte Version { get; set; }
}

But to be able to use that class we need to decode the incoming bytes in some way. So let’s create our first pipeline handler which we’ll use for just that:

public class HeaderDecoder : IUpstreamHandler
{
	public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		var msg = message as Received;
		if (msg == null)
		{
			context.SendUpstream(message);
			return;
		}

		// byte + int
		if (msg.BufferSlice.RemainingLength < 5)
		{
			return;
		}

		var header = new SimpleHeader
						 {
							 Version = msg.BufferSlice.Buffer[msg.BufferSlice.Position++],
							 Length = BitConverter.ToInt32(msg.BufferSlice.Buffer, msg.BufferSlice.Position)
						 };
		msg.BufferSlice.Position += 4;
		context.SendUpstream(new ReceivedHeader(header));

		if (msg.BufferSlice.RemainingLength > 0)
			context.SendUpstream(msg);
	}
}

Pretty straightforward. We don’t process anything until we got at least five bytes (the channel will continue to fill the buffer at the end until we handle something). Then we just decode the header, send a RecievedHeader message and pass on the remaining bytes. Notice that I use the version byte first. By doing so we can change the header as much as we like in future versions without screwing everything up.

The header doesn’t say anything more than the size of the actual JSON message. So we need something to process the JSON to. Let’s create another upstream handler for that (and thefore complying with the Single Responsibility Princinple). At will be called… BodyDecoder ;) (I’ve cheated and created the Request/Response/Error objects which the JSON RPC specification describes.)

public class BodyDecoder : IUpstreamHandler
{
	private static readonly BufferPool _bufferPool = new BufferPool(65535, 50, 50);
	private readonly BufferPoolStream _stream;
	private SimpleHeader _header;

	public BodyDecoder()
	{
		var slice = _bufferPool.PopSlice();
		_stream = new BufferPoolStream(_bufferPool, slice);
	}

	public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		var headerMsg = message as ReceivedHeader;
		if (headerMsg != null)
		{
			_header = headerMsg.Header;
			if (_header.Length > 65535)
			{
				var error = new ErrorResponse("-9999", new RpcError
														   {
															   Code = RpcErrorCode.InvalidRequest,
															   Message =
																   "Support requests which is at most 655355 bytes.",
														   });
				context.SendDownstream(new SendResponse(error));
			}

			return;
		}

		var received = message as Received;
		if (received != null)
		{
			var count = Math.Min(received.BufferSlice.RemainingLength, _header.Length);
			_stream.Write(received.BufferSlice.Buffer, received.BufferSlice.Position, count);
			received.BufferSlice.Position += count;

			if (_stream.Length == _header.Length)
			{
				_stream.Position = 0;
				var request = DeserializeRequest(_stream);
				context.SendUpstream(new ReceivedRequest(request));
			}

			return;
		}

		context.SendUpstream(message);
	}

	protected virtual Request DeserializeRequest(BufferPoolStream body)
	{
		var reader = new StreamReader(body);
		var json = reader.ReadToEnd();
		return JsonConvert.DeserializeObject<Request>(json);
	}
}

Here we are using the BufferPool instead of creating a new buffer each time. Hence a quite large performance gain and a lot less fragmented memory if the server runs for a while. Also notice that the framework has a BufferPoolStream which uses the BufferPool to get byte[] buffers. Future versions of the stream will most likely be able to use several buffers behind the scenes (and therefore be able to handle larger amount of data without creating too large buffers).

Before we continue with the actual application, lets add the only downstream handler. The response encoder.

public class ResponseEncoder : IDownstreamHandler
{
	private static readonly BufferPool _bufferPool = new BufferPool(65535, 50, 100);

	public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		var msg =  message as SendResponse;
		if (msg == null)
		{
			context.SendDownstream(message);
			return;
		}

		var result = JsonConvert.SerializeObject(msg.Response, Formatting.None);

		// send header
		var header = new byte[5];
		header[0] = 1;
		var lengthBuffer = BitConverter.GetBytes(result.Length);
		Buffer.BlockCopy(lengthBuffer, 0, header, 1, lengthBuffer.Length);
		context.SendDownstream(new SendBuffer(header, 0, 5));

		// send JSON
		var slice = _bufferPool.PopSlice();
		Encoding.UTF8.GetBytes(result, 0, result.Length, slice.Buffer, slice.StartOffset);
		slice.Position = slice.StartOffset;
		slice.Count = result.Length;
		context.SendDownstream(new SendSlice(slice));
	}
}

Now we only got one thing left to do in the pipeline. And that’s to handle the requests. Let’s start by creating a very simple handler:

class MyApplication : IUpstreamHandler
{
	public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		var msg = message as ReceivedRequest;
		if (msg == null)
			return;


		var parray = msg.Request.Parameters as object[];
		if (parray == null)
			return; // muhahaha, violating the API specification

		object result;
		switch (msg.Request.Method)
		{
			case "add":
				result = int.Parse(parray[0].ToString()) + int.Parse(parray[0].ToString());
				break;
			case "substract":
				result = int.Parse(parray[0].ToString()) + int.Parse(parray[0].ToString());
				break;
			default:
				result = "Nothing useful.";
				break;
		}

		var response = new Response(msg.Request.Id, result);
		context.SendDownstream(new SendResponse(response));
	}
}

How do we run the application then? We need to create a server channel and define the client pipeline. I usually do it in a class called XxxxListener to follow the .NET standard. So let’s create a JsonRpcListener.

public class JsonRpcListener : IUpstreamHandler, IDownstreamHandler
{
	private TcpServerChannel _serverChannel;
	private Pipeline _pipeline;


	public JsonRpcListener(IPipelineFactory clientFactory)
	{
		_pipeline = new Pipeline();
		_pipeline.AddDownstreamHandler(this);
		_pipeline.AddUpstreamHandler(this);
		_serverChannel = new TcpServerChannel(_pipeline, clientFactory, 2000);

	}

	public void Start(IPEndPoint endPoint)
	{
		_pipeline.SendDownstream(new BindSocket(endPoint));
	}

	public void Stop()
	{
		_pipeline.SendDownstream(new Close());
	}

	public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		var msg = message as PipelineFailure;
		if (msg != null)
			throw new TargetInvocationException("Pipeline failed", msg.Exception);
	}

	public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
	{
		context.SendDownstream(message);
	}
}

So now we can define the client pipeline in Program.cs and inject it in the RpcListener:

class Program
{
	static void Main(string[] args)
	{
		LogManager.Assign(new SimpleLogManager<ConsoleLogger>());

		var factory = new DelegatePipelineFactory();
		factory.AddUpstreamHandler(() => new HeaderDecoder());
		factory.AddUpstreamHandler(() => new BodyDecoder());
		factory.AddUpstreamHandler(new MyApplication());
		factory.AddDownstreamHandler(new ResponseEncoder());

		JsonRpcListener listener = new JsonRpcListener(factory);
		listener.Start(new IPEndPoint(IPAddress.Any, 3322));

		Console.ReadLine();
	}
}

The first two upstream handlers are stateful, so we need to create those for every channel which is generated. That’s why we use a delegate. The last two is not stateful and can therefore be singletons.

That’s it. You now got a working JSON RPC server. Sure. It’s pretty basic, but the actual remoting layer doesn’t have much to do with the networking layer. I did however take some time to create a proof of concept RPC system. Let’s define our RPC service first:

public class MathModule
{
	[OperationContract]
	public int Sum(int x, int y)
	{
		return x + y;
	}
}

Then we need to redefine the client pipeline:

var invoker = new RpcServiceInvoker(new DotNetValueConverter(), new SimpleServiceLocator());
invoker.Map<MathModule>();

factory.AddUpstreamHandler(() => new HeaderDecoder());
factory.AddUpstreamHandler(() => new BodyDecoder());
factory.AddUpstreamHandler(new RequestHandler(invoker));
factory.AddDownstreamHandler(new ResponseEncoder());

That’s it. From here we could go and include the Http protocol implementation and switch out our simple header against the HeaderDecoder in the HTTP implementation and therefore get an implementation which works over HTTP instead of our basic binary header. We have to do a few minor changes to achieve that, keeping most of the Json RPC implementation intact.

Summary

I hope that I’ve managed to demonstrate how to develop networking applications with Griffin.Networking and show the power that it gives you compared to vanilla .NET socket servers.

The code is available as a nuget package griffin.networking and the http implementation is available as griffin.networking.http. The JSON RPC implementation is still just a concept and therefore not added as a release yet. Feel free to participate to complete it.

All code is also available at github.


Griffin.MvcContrib – The plugin system

Introduction

Griffin.MvcContrib is a contribution project for ASP.NET MVC3 which contains different features like extendable HTML Helpers (you can modify the HTML that the existing helpers generate), easy localization support and a quite fresh support for plugin development. The purpose of this article is to provide a step-by-step instruction on how you can develop plugins using Griffin.MvcContrib.

Using the code

The plugin support are based on the Area support which MVC3 got. If you haven’t used areas before, I suggest that you start by reading the following article.

Most basic approach.

This first sample is not really a plugin system but only showing how you can move your code to class libraries. The example will only contain one class library to avoid confusion.
Start by creating a new ASP.NET MVC3 project (of any kind) and a class library project. For convenience we would like to have support for Razor and all MVC3 wizards in our class library. It helps us add some basic files which are required to get everything working.
To get that support we need to modify the project file for the class library. Here is how:

1. Right-click on the class library project and choose unload project:

2. Right-click on the project file and select Edit project file

3. Add the following XML element on a new line below <ProjectGuid>

<ProjectTypeGuids>{E53F8FEA-EAE0-44A6-8774-FFD645390401};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>  

4. Save and close the project file.

5. Right-click and reload the project.

6. Add reference to “System.Web” and “System.Web.Mvc” (project settings)

You have now told Visual Studio that it should active the tooling and Razor 3 views. We can now add an area by just right-clicking on the project and select “Add Area”.

Do so and create an area with a name of your choosing. Create a controller (with an Index action) and a view for the index action. You now got your first external DLL for the MVC project.

Add a reference to the class library from the MVC3 project:

Congratulations. You now got your first “plugin” based solution. Hit F5 to run the project. I named my area “Ohh” and my controller “My” so I surf to “http://theHostNameAndPort/ohh/my” to visit my plugin controller.

Uh oh. We can visit the page alright. But the view cannot be found. It can be solved thanks to Griffin.MvcContrib. Let’s install the project in the MVC3 project:

Then open up global.asax and create a new method which maps the views:

protected void Application_Start()
{ 
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    RegisterViews();
}
protected void RegisterViews()
{
    var embeddedProvider = new EmbeddedViewFileProvider(HostingEnvironment.MapPath("~/"), new ExternalViewFixer());
    embeddedProvider.Add(new NamespaceMapping(typeof(Lib.Areas.Some.Controllers.MyController).Assembly, "BasicPlugins.Lib"));
    GriffinVirtualPathProvider.Current.Add(embeddedProvider);
    HostingEnvironment.RegisterVirtualPathProvider(GriffinVirtualPathProvider.Current);
} 

The first line creates a new file provider which loads files from embedded resources. We tell it which path it should try to provide files for. The next line simply adds our class library assembly and tell which root namespace it has. To make this work, we also have to change our view to an embedded resource:

Everything should be set now. Hit F5 and visit the area controller again. You should see the view now.

You can also try to have a break point in the class library. Debugging should work just like it used to. There is still one “problem”. We can’t modify the views at runtime, we need to recompile the project each time we adjust a view. Fortunually for us, Griffin.MvcContrib can solve that too. Open the RegisterViews method in global.asax again. Let’s add a disk file provider. It should be added before the embedded provider since the first found file will be used.

var diskLocator = new DiskFileLocator();
diskLocator.Add("~/", Path.GetFullPath(Server.MapPath("~/") + @"..BasicPlugins.Lib"));
var viewProvider = new ViewFileProvider(diskLocator);
GriffinVirtualPathProvider.Current.Add(viewProvider);  

You can now edit the views at runtime.

Building a plugin system

The last part showed you how you can put Controllers, Models and Views in class libraries. It’s quite useful as long as you don’t want to develop features in a more loosely coupled and dynamic way. This section will suggest a structure which you can use when building plugins.

The following part expects you to have used inversion of control containers in the past. The container is used to provide the application extension points to all plugins. I prefer using a container which has a module system so that each plugin can take care of all it’s registrations itself. I’m using Autofac in this article and it’s Module extension.

Let’s place all code which is shared between the plugins and the MVC3 project in a seperate class library. You could also follow follow the Separated interface pattern and only define all interfaces in that project. Thus removing all direct dependencies between the plugins and the main application.

The last thing to remember is that the default route configuration doesn’t work very well if you have controllers with the same name in different areas. To overcome that you have to manually change all route mappings to include the namespace. Also remove the “_default” from the route name.

Modified registration:

public override void RegisterArea(AreaRegistrationContext context)
{
	context.MapRoute(
		"Messaging_default",
		"Messaging/{controller}/{action}/{id}",
		new { action = "Index", id = UrlParameter.Optional },
		new[] { GetType().Namespace + ".Controllers" }
	);
}

Create a new class library named something like “YourApp.PluginBase” and add our basic extension points:

public interface IRouteRegistrar
{
	void Register(RouteTable routes);
}

Used to register any custom routes.

public interface IMenuRegistrar
{
	void Register(IMenuWithChildren mainMenu);
}

Allows the plugins to register themselves in the main application menu.

We’ll just use those two extensions in this example. Feel free to add as many extensions as you like in your own project ;)

The structure

We’ll need to have some structure for the plugins so that the can easily be managed, both during development and in production. All plugins will therefore be placed in a sub directory called “Plugins”. Something like:

ProjectName\Plugins
ProjectName\Plugins\PluginName
ProjectName\Plugins\PluginName\Plugin.PluginName
ProjectName\Plugins\PluginName\Plugin.PluginName.Tests
ProjectName\ProjectName.Mvc3

Add a new solution folder by right-clicking on the solution folder in the Solution Explorer. Do note that solution folders doesn’t exist on the disk and you’ll therefore have to manually append the folder to the location text box each time you add a new project in it.

Right-click on the Plugins folder in Solution Explorer and add a new project named “PluginName”. Don’t forget to append PluginsPlugin.Name to the location text box.

Since we this time don’t want to have any references to the plugins from the main application we have to manually copy them to the main application plugin folder. We use a post build event for that. Don’t forget to copy in all dependencies that your project has, since nothing handles that for you (the price of having no direct references from the MVC3 project to the plugins).

Complete structure:

Menu items

Keep in mind that you can not unload plugins and that they are available for all users. The easiest way to come around that is to display menu items only if the user has a role, which means that you should create one (or more) role(s) per plugin (if the plugin should not be available for all users). Griffin.MvcContrib contains a basic menu implementation which allows you to control if menu items are visible or not.

Sample code:

var item = new RouteMenuItem("mnuMyPluginIndex", "List messages", new { 
        controller = "Home", 
        action = "Index", 
        area = "Messages"});
item.Role = "MessageViewer";
menuRegistrar.Add(item);

You can later use menuItem.IsVisible when you generate the menu to determine if the item should be included or not.

Hello container

For this exercise we’ll use Autofac as the container. It contains a nifty module system which aids us in keeping the projects loosely coupled. Each plugin need to create a class which inherits from Autofac.Module and use that class to register all services which the plugin provides. Thanks to that we’ll just have to scan all plugin assemblies after any container modules and invoke them with our container.

public class ContainerModule : Module
{
	protected override void Load(ContainerBuilder builder)
	{
		builder.RegisterType<MenuRegistrar>().AsImplementedInterfaces().SingleInstance();
		builder.RegisterType<HelloService>().AsImplementedInterfaces().InstancePerLifetimeScope();
		base.Load(builder);
	}
}

The plugins are loaded from the main application using the following snippet:

var moduleType = typeof (IModule);
var modules = plugin.GetTypes().Where(moduleType.IsAssignableFrom);
foreach (var module in modules)
{
	var mod = (IModule) Activator.CreateInstance(module);
	builder.RegisterModule(mod);
}

Views during development

Since we want to be able to modify views at runtime during development we have to tell ASP.NET MVC3 where it can find our plugin views. We do this by using GriffinVirtualPathProvider and a custom file locator which looks like this:

public class PluginFileLocator : IViewFileLocator
{
    public PluginFileLocator()
    {
        _basePath = Path.GetFullPath(HostingEnvironment.MapPath("~") + @"..Plugins");
    }

    public string GetFullPath(string uri)
    {
        var fixedUri = uri;
        if (fixedUri.StartsWith("~"))
            fixedUri = VirtualPathUtility.ToAbsolute(uri);
        if (!fixedUri.StartsWith("/Areas", StringComparison.OrdinalIgnoreCase))
            return null;

        // extract area name:
        var pos = fixedUri.IndexOf('/', 7);
        if (pos == -1)
            return null;
        var areaName = fixedUri.Substring(7, pos - 7);

        var path = string.Format("{0}{1}\Plugin.{1}{2}", _basePath, areaName, fixedUri.Replace('/', '\'));
        return File.Exists(path) ? path : null;
    }
}

It simply takes the requested uri and converts it using the naming standard I described above. Everything else is taken care of by Griffin.MvcContrib.

And interesting part is that the provider is only loaded during development thanks to nifty helper class in Griffin.MvcContrib:

if (VisualStudioHelper.IsInVisualStudio)
    GriffinVirtualPathProvider.Current.Add(_diskFileProvider);

Loading the plugins

Ok. We’ve created some plugins (and their dependencies) which are copied to the bin folder with a post build event. We’ll therefore have to load them in some way. To do this we create a new class looking like this:

public class PluginService
{
    private static PluginFinder _finder;
    private readonly DiskFileLocator _diskFileLocator = new DiskFileLocator();
    private readonly EmbeddedViewFileProvider _embededProvider =
        new EmbeddedViewFileProvider(new ExternalViewFixer());
    private readonly PluginFileLocator _fileLocator = new PluginFileLocator();
    private readonly ViewFileProvider _diskFileProvider;

    public PluginService()
    {
        _diskFileProvider = new ViewFileProvider(_fileLocator, new ExternalViewFixer());

        if (VisualStudioHelper.IsInVisualStudio)
            GriffinVirtualPathProvider.Current.Add(_diskFileProvider);

        GriffinVirtualPathProvider.Current.Add(_embededProvider);
    }


    public static void PreScan()
    {
        _finder = new PluginFinder("~/bin/");
        _finder.Find();
    }

    public void Startup(ContainerBuilder builder)
    {
        foreach (var assembly in _finder.Assemblies)
        {
            // Views handling
            _embededProvider.Add(new NamespaceMapping(assembly, Path.GetFileNameWithoutExtension(assembly.Location)));
            _diskFileLocator.Add("~/",
                                 Path.GetFullPath(HostingEnvironment.MapPath("~/") + @"...." +
                                                  Path.GetFileNameWithoutExtension(assembly.Location)));

            //Autofac integration
            builder.RegisterControllers(assembly);
            var moduleType = typeof (IModule);
            var modules = assembly.GetTypes().Where(moduleType.IsAssignableFrom);
            foreach (var module in modules)
            {
                var mod = (IModule) Activator.CreateInstance(module);
                builder.RegisterModule(mod);
            }
        }
    }

    // invoke extension points
    public void Integrate(IContainer container)
    {
        foreach (var registrar in container.Resolve<IEnumerable<IMenuRegistrar>>())
        {
            registrar.Register(MainMenu.Current);
        }

        foreach (var registrar in container.Resolve<IEnumerable<IRouteRegistrar>>())
        {
            registrar.Register(RouteTable.Routes);
        }
    }
}

The plugins are now loaded and the extension points have been passed to them.

Final touch

The last thing to change is global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    _pluginServicee = new PluginService();
    RegisterContainer();
    HostingEnvironment.RegisterVirtualPathProvider(GriffinVirtualPathProvider.Current);
    _pluginServicee.Integrate(_container);
}

private void RegisterContainer()
{
    var builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly());
    _pluginServicee.Startup(builder);
    _container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
}

Code

The code for the samples are located in github and so is Griffin.MvcContrib. Griffin.MvcContrib can also be install from nuget.