Enabling Add-In functionality in ASP.NET MVC 3

Crossposted from my personal blog.

Update:  Part 2

I remember, back in 2006 when I wrote my first managed add-in for AutoCAD. The fact that we could extend the functionality of a very big product, using .NET was huge. Till that time, if we wanted to use .NET for add-in functionality we had to rely on RCW or else we had to write messy and error-prone VBA code. 

Today, anyone who builds applications in managed code (using .NET 4 and above) has built-in functionality for extensibility provided by the framework itself. In this post, we will be extending an ASP.NET MVC 3 application. We are going to use Unity as the Dependency Injection (DI) container and the types from the System.ComponentModel.Composition namespace (or else, MEF) for managing the composition of parts.

The host application, is the one shown below. I have selected the interesting types that I will be discussing.

HostSolutionTree

DiscoverableControllerFactory

A MEF-specific DefaultControllerFactory derived type. It gets the exported types with the contract name, derived from an IController type. After the controller is supplied, the MVC framework will resolve the Views.

UnityControllerFactory

A Unity-specific DefaultControllerFactory  derived type. There are many implementations around. The difference from other implementations is that this one takes a delegate as a parameter in the constructor that acts as the fallback factory when the DI container can not supply a controller. This is a very important part of our architecture because here we have the chance to supply the target controller (as an add-in) using MEF.

Global.asax

Here we specify the default path for the extensions. We create a new instance of the DiscoverableControllerFactory class passing a CompositionContainer and a DirectoryCatalog. Keep in mind that the DirectoryCatalog is one of the many choices that MEF provides for discovering parts. Besides the creation of the DiscoverableControllerFactory we also create a new instance of the UnityControllerFactory class acting as the default controller factory. Any controllers that this factory can not supply will fallback to the DiscoverableControllerFactory using it’s CreateController method. One last thing to note, this is the application’s Composition Root. The DI container is referenced here, where the composition happens, and nowhere else in the entire application.

The add-in application is a regular class library and it’s structure is shown below. I have selected the interesting types that I will be discussing.

AddInSolutionTree

ConceptController

This is a proof of concept Controller for this demo. It is decorated with the ExportAttribute and ExportMetadataAttribute. The later is needed in order to help the DiscoverableControllerFactory to choose the right controller among all the controllers supplied by this and other add-ins. The PartCreationPolicyAttribute is needed in order to specify that a new non-shared (transient) instance will be created for each request.

Index.cshtml, Web.config

Nothing special to say here. The razor view is just any other (razor) view. The Web.config is needed as a hint for the MVC framework to compile the razor views at runtime.

Make sure to select all the views and set the property “Copy to Output directory” to “Copy if newer”. This is important because each time we compile the add-in library besides the .dll with the models and the controllers we also want the views to be copied there (they are also part of the add-in).

You can download the demo application here. Upon build the Concepts.dll along with it’s Views will be copied in the Web project’s “Extensions” directory. When run, the application will automatically load the assembly the first time the “Concepts” tab is pressed.

Following the Composition Root pattern with Enterprise Library

Crossposted from my personal blog.

A question that frequently rises when building enterprise applications is: “Where should we compose object graphs?” and the answer is given by the Composition Root pattern: “As close as possible to the applications entry point.”

The Composition Root pattern is described in the excellent book, Dependency Injection in .NET by Mark Seemann.

Here is the definition from the book:

A Composition Root is a (preferably) unique location in an application where modules are composed together.

When working with the Enterprise Library, it is very common to hide the complexities of initial context creation by using the built-in IServiceLocator implementation provided by the EnterpriseLibraryContainer class.

Since I completely agree with the statement “Service Locator is an Anti-Pattern” I would like to compose all Enterprise Library modules in the Composition Root. Then, I can use well-known DI patterns (such as Constructor Injection) to supply the Dependencies.

Fortunately, the EnterpriseLibraryContainer class contains a method named “ConfigureContainer” that reads the current configuration and supplies the corresponding type information to configure a dependency injection container (by default Unity).

After, configuring the container in the Composition Root we can resolve any instance of a type from Enterprise Library as with any other object.

JSF labels and messages from DB

The following is a step-by-step tutorial on how to implement the retrieval of jsf labels and messages from a database instead of the usual message resource bundles.

1. Create db tables

We’ll create 3 tables, one for the messages (MESSAGE), one for the supported locales (SUPPORTEDLOCALE) and one for the web applications that need localized messages (INTERNALAPPLICATION). The Message table should have columns for id, application name, locale (foreign key - the id of locale table), message key and message value. The SupportedLocale table should have columns for id, locale and locale description. Finally the InternalApplication (INTERNALAPPLICATION) table should have columns for id, application name and locale (foreign key - the id of locale table).

2. Create POJOs

Create 3 classes with attributes mapped by the table columns.

3. Create dao and hibernate mapping

Create 2 methods – one for retrieving locales (select * from locale) and one for retrieving messages taking as parameter the locale string (select m from Message m join m.supportedLocale sl where sl.locale=?).

Create messages.hbm.xml file for the mapping.

4. Create service

Create 2 methods that each call the appropriate dao method and return transfer objects as a result.

5. Create message provider class

Create a class that extends HashMap and override method get(Object key).

Call the service method to retrieve all locales and for each supported locale create a map that contains the locale string and a map with the key and value (e.g. localeMaps = new HashMap<locale, Map<key, value>>();). Next, call the service method passing the locale as parameter to retrieve the messages and add the key and the value to the map.

Finally, find the current locale of the application and get the corresponding key.

FacesContext context = FacesContext.getCurrentInstance();
String applicationLocale = context.getViewRoot().getLocale().getLanguage();

value = localeMaps.get(applicationLocale).get(key);

In faces-config.xml define a managed bean with name the resource bundle var and ‘application’ scope and that’s it!!

SOA Antipatterns

Interesting article in Oracle about SOA anti-patterns. I am tempted to add the lack of real knowledge of what SOA really means and requires. Just like a boy who dares saying in front of his mates that he’s not aware of the new football star in town, most IT professionals pretend understanding the benefits of SOA and are willing to work in such an environment, while in reality they do not even know what it is all about.

Solution: Better educate all professionals playing a role in the new architecture or – even better – have them participate in pilot implementations of the new architecture.