Using Dependency Injection with an ObjectDataSource

In this post I will outline how to use dependency injection with an ObjectDataSource.  There are many benefits to using dependency injection and programming to interfaces including maintainability, extensibility, and testability.  For the example that follows the use case is to provide a pagable, sortable list of data, using a gridview, and performing the paging and sorting within the database for performance reasons.  Based on these requirements, an object data source is needed as it provides the mechanism to support custom paging and sorting for a grid view.

Dependency Injection For this example I have choosen StructureMap.  One of the nice features of StructureMap is that is allows you to map your Interfaces to concrete types using code.  The below code creates a Registry and leverages some new features in StrucutreMap version 2.5

public class ServiceRegistry : Registry
  protected override void configure()

This code instructs StructureMap to return PersonRepository when someone requests an IPersonService. There is a lot more you can do with StructureMap, for a complete overview of StructureMap, please check out their homepage.

Next, it is time to set up the ObjectDataSource.  An ObjectDataSource does not let you specify an Interface directly, so you need to override the default behavior.  First, define the types:

<asp:ObjectDataSource ID="ObjectDataSourcePerson" runat="server" SelectMethod="GetRecordList"        DataObjectTypeName="Services" TypeName=Services.IPersonService"        OnObjectCreating="ObjectDataSourcePerson_ObjectCreating" >   

The important things to note are the types (DataObjectTypeName is Namespace.Class, TypeName is Namespace.Class.Type) and the OnObjectCreating, this is where we will override the default behavior.  The code behind for this looks like: 

protected void ObjectDataSourcePerson_ObjectCreating(object sender, ObjectDataSourceEventArgs e)    {        
IPersonService personService =
e.ObjectInstance = personService;

Now, when the ObjectDataSource is created, the concrete type will be used.  The power here is that we did not have to specify the concrete type in the code or DataSource definition, so in the future we can change the implementation and not need to change the UI code.

From here, you can implement the paging and sorting in the custom type and wire it up to the ODS and GridView.