Monday, December 22, 2008

Using Dependency Injection with CSLA.NET

In this post, I'm going to talk about one way to implement Dependency Injection with CSLA.NET
NOTE: My discussions and code samples are using CSLA.NET 3.5.


CSLA.NET.  I'm a big fan.  I have been even back before it went .NET in the VB5 and VB6 days.
I don't know actual statistics, but I would wager that CSLA.NET is probably the most popular framework for creating object-oriented business objects in .NET.  If you're building even a moderately complex line-of-business application where you want your business logic to live in one place (instead of spread all over the place, the worst being in your UI), you want a middle tier that takes advantage of object-oriented design (not just a set of classes that mimic the structure of the database), and optionally have everything just work in a distributed environment, then you should definitely take a close look at CSLA.NET.
I'm also a big fan of automated tests around my business layer.  And when I say tests, I'm referring to unit tests, where I want to validate just the behavior of my business object and nothing else.  In other words, I'm not interested in testing the other layers that my business object may interact with (like the database or a logging component).  Those would be integration or regression tests.  Those are good too, by the way, but unit tests should come first.
Since business objects almost always have to communicate with other layers, your unit tests need the ability to fake those layers out in order to test your business logic in isolation.  There are variety of ways to do this, but a popular one is to abstract calls to these layers using Dependency Injection and then use a mocking framework to inject a fake version of that layer.  To really do Dependency Injection, you need to use a framework of some kind (typically called an IOC Container) to handle your dependency instances and automatically perform injections on your objects.


So, like I said, I really love the CSLA.NET framework.  But with all of its awesome excellence, I've always been challenged writing true unit tests against business objects that use it.  This is because CSLA.NET makes it difficult to implement Dependency Injection.  Why?  In short: CSLA.NET creates your business object instances for you.  This happens in the servers-side portion of the DataPortal.  Dependency Injection works best if it can have some kind of access to the object creation process so an object's dependencies can be injected.  Unfortunately, the DataPortal does not provide any sort of hook where you can create your object.  The DataPortal does this all behind the scenes as a black box and then gives you your object instance after creation, letting you then execute your data-access code in the DataPortal_* methods.
To be fair, the latest version of CSLA.NET, 3.6 which just released, does give you access into the creation of your business objects via the new object factory feature.  However, there are two challenges with going down this road:
  1. You end up having to write a lot more than just object creation into your object factory classes since the object factory is also responsible for performing all data access including the state population of your business objects. 
  2. You have to write a factory class for every business object that requires dependency injection.  Couple this with the first point, and that adds up to a lot more coding just so you can have control over the creation of your business objects.
There is also another challenge, and that is that the creation of objects on the server-side of the DataPortal isn't the only place business objects in CSLA.NET are being created!  One of the great features of CSLA.NET is this idea of mobile objects: your business objects have the ability to be transported from one physical tier to another.  However, every time an object goes mobile it needs to be serialized.  When it gets to the destination tier, it needs to be deserialized and deserialization involves recreating the object instance except this time its done within the bowels of the .NET Framework.  Yuck!  Even more difficult to hook into.  And by the way, as of CSLA.NET 3.5, for consistency this serialization/deserialization process even occurs when everything happens in-process on one physical tier.


The solution I finally stumbled upon essentially gave up on the idea of trying to hijack the object creation process either in the DataPortal or worse yet in the .NET Framework itself during deserialization. 
The good news is that most IOC Container frameworks out there allow you to perform dependency inject with an existing object instance.  In my case, I'm using Unity, the IOC Container from Microsoft, which is a member of their Application Blocks family.  Unity's container object has a method called BuildUp that let's you do exactly this.
And the other piece of good news is that CSLA.NET allows very easy access to an object instance just after it is created either by the server-side DataPortal or by deserialization.  All you have to do is override a couple virtual methods and you're done!


My implementation of this was to create a set of base classes that all inherit from main CSLA.NET base classes that do the necessary overrides and perform the dependency injection.  Let's build the base class for BusinessBase<T>, probably the most used CSLA.NET base class.
First, let's get the basics out of the way.  We'll declare an abstract class called InjectableBusinessBase<T> that inherits from BusinessBase<T> and contains a protected constructor, which all abstract classes should have:
public abstract class InjectableBusinessBase<T>
    : BusinessBase<T>
    where T : BusinessBase<T>

    protected InjectableBusinessBase() { }

Now, let's add the necessary overrides to hook into post-object creation so we can kick off our dependency injection:
    protected override void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)

    protected override void Child_OnDataPortalInvoke(DataPortalEventArgs e)

    protected override void OnDeserialized(StreamingContext context)
First we overrode DataPortal_OnDataPortalInvoke.  This gets called by the server-side DataPortal when a root level business object is created.  Then we overrode Child_OnDataPortalInvoke which gets called by the server-side DataPortal whenever a child object is created by the DataPortal (a new feature as of CSLA.NET 3.5 that I highly recommend).  Finally, we overrode OnDeserialized, which, through the help of BusinessBase<T>, gets called by the deserialization process of .NET.
In all three cases, we're calling an Inject method, which is a private method declared in our base class.  It looks like this:
    private void Inject()
        var type = this.GetType();
        Ioc.Container.BuildUp(type, this);
Nothing too fancy here.  We're essentially calling the Unity BuildUp method which requires the type of our business object and the business object instance itself.
What is a little exotic, if you're familiar with Unity, is the Ioc.Container code.  Our base class needs some way to access the Unity container instance against which to call BuildUp.  I've created a utility class called Ioc that has a static Container property that returns this.  I'll include the code for this class as well as all the code for the various base classes at the end of this post.  For now, just know that the code Ioc.Container returns our IOC container.
That pretty much is all that's required to make dependency injection  work with CLSA.NET and Unity!  However, I do have one more method I want to include in my base class:
    protected TDependency EnsureDependency<TDependency>(TDependency dependency) 
        where TDependency : class
        if (dependency == null)
            throw new MissingDependencyInjectionException(this.GetType(), typeof(TDependency));
        return dependency;
The purpose of this method will become a little more clear when we take a look at an example concrete business object class that inherits from InjectableBusinessBase<T>.  Essentially all this method does is return the same object that gets passed in.  However, before it returns it, the method checks to make sure the object is null; if so, it throws a custom exception that basically says a required dependency instance is missing that it's of a certain type and is contained within the object of this type.  I'll include the source code for this exception class at the end of the post as well.

Sample Concrete Class

To make all this gel, let's code up a concrete business object class that inherits from our base class.  I'm going to code up a very simple Customer class that has two properties, ID and Name, and a single Fetch factory method.  Here's the code so far:
public sealed class Customer
    : InjectableBusinessBase<Customer>

    private static PropertyInfo<int> IdProperty = 
        RegisterProperty<int>(new PropertyInfo<int>("Id"));
    public int Id
        get { return GetProperty<int>(IdProperty); }

    private static PropertyInfo<string> NameProperty = 
        RegisterProperty<string>(new PropertyInfo<string>("Name"));
    public string Name
        get { return GetProperty<string>(NameProperty); }
        set { SetProperty<string>(NameProperty, value); }

    private Customer() { }

    public static Customer Fetch(int id)
        var criteria = new SingleCriteria<Customer, int>(id);
        return DataPortal.Fetch<Customer>(criteria);
Nothing new here other than the class inherits from InjectableBusinessBase<Customer>.  We have two properties declared using the new CSLA.NET 3.5 managed property syntax.  Then we have the standard private constructor and the static factory method which uses the DataPortal to create and fetch our business object from the database.
Now I want to introduce a dependency into my class that performs the actual data access necessary to fetch the customer, which will be performed in a standard DataPortal_Fetch method.  This data access object will implement a custom interface called ICustomerDataAccess and will have a method called FetchData that takes a customer ID and returns a DTO that contains my customer data.  Here's what my ICustomerDataAccess interface might look like:
public interface ICustomerDataAccess
    ICustomerDto FetchData(int id);
By the way, a DTO (data transfer object) is just an object that contains nothing but data.  For mocking purposes, my DTO is an interface (called ICustomerDto). 
In an upcoming post, I'll show a more elegant way to abstract away the data access layer in CSLA.NET using dependency injection and the Repository pattern.
Let's add a field to my class that will contain this dependency:
    private ICustomerDataAccess _dataAccess;
Notice that I've added two attributes to this field.  The first, NonSerializedAttribute, is important because we don't want this dependency (or probably any dependency) to be serialized if the business object were to become mobile and transferred from one physical tier to another.  In the case of data access, it really only needs to occur on the tier that performs data access (i.e. an application server).
The second attribute, NotUndoableAttribute, comes from the CSLA.NET framework.  It tells CSLA.NET that this field is not to participate in the undo functionality provided by the BusinessBase<T> class.  This is because the dependency does not contain any business object state that would need to be rolled back if the users were to perform an Undo.
Having both of these attributes in place essentially relieves us of the need to make our dependency serializable.  The actual implementation class of ICustomerDataAccess can be just a plain old object.
Now we need a way to inject this dependency into our business object.  Unity gives you three ways: constructor, set-able property, or method.  We can't use the Customer constructor since we're performing the dependency injection after the instance has been created by the DataPortal or deserialization.  We could use the set-able property.  However, I personally like the method approach since, if you have multiple dependencies, you can inject all of them in a single call. 
We just have one in our example, so here's the code:
    public void Inject(ICustomerDataAccess dataAccess)
        if (dataAccess == null)
            throw new ArgumentNullException("dataAccess");
        _dataAccess = dataAccess;
My method can be named anything, but it needs to be decorated with the special Unity InjectionMethodAttribute and it needs a parameter for each of my dependencies so I can set the fields.  Notice I also throw an ArgumentNullException if whatever is doing the injection passes in a null.  We want to fail if this ever happens.
Finally, we need to add the DataPortal_Fetch method that will use our data access dependency:
    private void DataPortal_Fetch(SingleCriteria<Customer, int> criteria)
        var customerData = EnsureDependency(_dataAccess).FetchData(criteria.Value);
        LoadProperty<int>(IdProperty, customerData.Id);
        LoadProperty<string>(NameProperty, customerData.Name);
The first thing we do is call the FetchData method of my ICustomerDataAccess object to obtain the customer DTO.  Here is where you can see the EnsureDependency method in action that we coded earlier in the base class.  If we wrap the _dataAccess dependency in a call to EnsureDependency, we know we're not going to get a NullReferenceException, which is non-descriptive and hard to debug.  Rather we'll get a more descriptive exception that explains exactly what dependency is missing from what object.
Once we have the DTO, we can simply populate our business object in the standard CSLA.NET 3.5 way.


There you have it!  Dependency Injection and CSLA.NET living peacefully side-by-side. 
If you'd like to take a look at the complete set of source code for this, which includes all the Injectable* base classes, the MissingDependencyInjectionException class, the Ioc helper class, and the sample Customer business object code, you can download it hereBefore the sample code will compile, you will also need to download CSLA.NET 3.5 and Unity 1.2 and update the assembly references accordingly.

UPDATE: The download link is actually now to the larger sample code set that demonstrates the Repository pattern (see these two blog posts for more details).  To see the DI-specific code discussed in the above blog post, check out the CslaRepositoryTest.Core namespace.

Now I'm not pretending that this is the only way to make this work.  If there are other people out there who've made Dependency Injection and CSLA.NET work better, perhaps with a different IOC Container like StructureMap or Castle Windsor, write a comment and let me know!

Monday, December 15, 2008

Trying out PreCode and SyntaxHighlighter

Per Scott Hanselman's recent blog post on the best code syntax highlighter for your blog, I'm giving his suggestion a try, which is to use the PreCode plug-in for Live Writer (a free blog writing GUI from Microsoft), which renders your code snippets so they use the SyntaxHighlighter JavaScript library. 

I host my blog on Google's Blogger and so I don't have an easy way to host the necessary JavaScript files to make SyntaxHighlighter work.  But I do have a Google Pages account, so I was able to upload them there and modify my blog's HTML Template in Blogger to include the necessary <link> and <script> tags to make the magic happen.  I used tips from this blog post to get it working.

I wanted to get this set up since I'm about to post three (yes three!) blog entries on CSLA.NET which will probably contain a fair amount of code.

Anyway, without further adieu, here's my first SyntaxHighlighter code snippet, generated by the PreCode plug-in:

public interface IFoo
void Bar();

public class MyFoo
: IFoo
public Bar()
//do something

NOTE: If you're using a feed reader like Google Reader, this code won't look like anything special.  You'll have to open the blog page directly to see the full effect.