Unity and RhinoMocks, I Like

On my current project we have been using Unity as a Dependency Injection Container. Previously to this project I had always created constructor overloads, so any dependencies could be injected for testing or replacement. Typically what I might have done would have looked something like this:

 public class MessageReceivingService : IMessageReceivingService
    {
        internal IMessageProcessor _MessageProcessor;
        internal IMessageRepository _MessageRepository;


        public MessageReceivingService()
            : this(new MessageProcessor(), new MessageRepository())
        { }

        public MessageReceivingService(IMessageProcessor messageProcessor, IMessageRepository messageRepository)
        {
            this._MessageProcessor = messageProcessor;
            this._MessageRepository = messageRepository;
        }

    }

The above allowed me to inject and change my dependencies. In a test I’d create mock objects for the dependent objects and call the constructor that takes the dependencies as parameters. The constructor with no parameters creates the default dependencies. A typical unit test looked like the below:

        private IMessageProcessor _MessageProcessorMock;
        private IMessageRepository _MessageRepositoryrMock;


        [TestInitialize]
        public void Setup()
        {
            this._MessageProcessorMock = MockRepository.GenerateMock<IMessageProcessor>();
            this._MessageRepositoryrMock = MockRepository.GenerateStub<IMessageRepository>();
        }


        [TestMethod]
        public void Checking_That_Some_Behavior_Works_Test()
        {
            //--Arrange
            MessageReceivingService serviceToTest =
                     new MessageReceivingService(this._MessageProcessorMock, this._MessageRepositoryrMock);

            Message testMessage = new Message();

            //--Act
            serviceToTest.ProcessMessages(testMessage);
            

            //--ASSERT
            this._MessageProcessorMock.AssertWasCalled(imd => imd.SaveMessage(Arg<PostOffice.Data.Message>.Is.Same(testMessage)));

        }

This allowed me to unit test and inject mocks. I was really only trying to allow myself the ability to inject mocks in unit testing. If it ever came up I could use the constructor overloads to override the default dependencies, but I was not that worried, that happened very infrequently.

What I did realize, and did not like, was that every time a dependency was added, I had to go change all my constructor calls in my unit test to allow for the new dependency. That was a pain, but not painful enough to make me change anything apparently.

Now that I started using Unity for DI The above class becomes this:

public class MessageReceivingService : IMessageReceivingService
    {
        internal IMessageProcessor _MessageProcessor;
        internal IMessageRepository _MessageRepository;
        internal IUnityContainer _Container;


        public MessageReceivingService()
            : this(new ConfiguredUnityContainer())
        { }

        public MessageReceivingService(IUnityContainer container)
        {
            this._Container = container;
            this._MessageProcessor = this._Container.Resolve<IMessageProcessor>();
            this._MessageRepository = this._Container.Resolve<IMessageRepository>();
        }

    }

ConfiguredUnityContainer is just a class extending UnityContainer that loads types from a default container in configuration. The above allows for an existing container to be passed in, or for a new one to be created and used. I wasn’t crazy about having dependencies to unity in my constructor, but I consoled myself since the dependencies were on the IUnityContainer interface and a class I had extended from UnityContainer.

It was in my unit tests that I realized how this was really going to help me. My unit test above now changed to this:


	private IMessageProcessor _MessageProcessorMock;
	private IMessageRepository _MessageRepositoryrMock;
	 
	[TestInitialize]
	public void Setup()
	{
	    this._MessageProcessorMock = MockRepository.GenerateMock<IMessageProcessor>();
	    this._MessageRepositoryrMock = MockRepository.GenerateStub<IMessageRepository>();
	}

[TestMethod]
        public void Checking_That_Some_Behavior_Works_Test()
        {
            //--Arrange
            IUnityContainer container = new UnityContainer();

            container.RegisterInstance<IMessageProcessor>(this._MessageProcessorMock);
            container.RegisterInstance<IMessageRepository>(this._MessageRepositoryrMock);

            MessageReceivingService serviceToTest =
                            new MessageReceivingService(container);

            Message testMessage = new Message();

            //--Act
            serviceToTest.ProcessMessages(testMessage);
            

            //--ASSERT
            this._MessageProcessorMock.AssertWasCalled(imd => imd.SaveMessage(Arg<PostOffice.Data.Message>.Is.Same(testMessage)));

        }

The first thing I realized was that I would no longer have to change my constructor if I added a dependency! Now my only constructor overload takes an IUnityContainer. I just set my dependencies in the test code, setting my mock objects as the served up dependencies. No matter how many dependencies I add or remove my constructors will never change.

As an added bonus, I can now replace dependencies on the fly. If I deliver a container that is mapped in a config file, I only have to change the config file to change served up dependencies. I was not really that worried about changing dependencies on the fly since it seemed to happen so rarely, but I certainly do not mind that it is now easy to do should the need arise.

I probably should have realized there was more value to a DI container then just serving up mocks in tests, but even in this context the DI container made my life easier. I have to say I really like the combination of Unity and RhinoMocks. I’m kicking myself for not looking into this myself before Unity was forced on me on a project!

Someone Recently Asked What Design Patterns I Used, Here’s What I Said.

There are a few design patters I use frequently, mainly because in business software the problems they are geared at solving come up often. The first is the Command pattern. This pattern in demonstrably useful in UI operations as it supports a generic means for undo and redo operations. When UI operations are implemented as atomic Command classes their undo redo operations are explicitly defined in a concrete object, and are generically invoked from the stack managing the executed commands as base commands. I have also come to find that the Command Pattern is very useful in pure business logic as well. In environments where distributed transactions are involved the Command pattern allows the definition of atomic transactions to be defined as a command in the business logic layer. The benefit of this structure is that each atomic Command can be chained and composite transaction behavior can be defined in the base Command class instead of by each operation itself.

There are two other patterns I use frequently to make code less coupled and more testable. The first, the Factory Pattern, was much more helpful before the wide acceptance of dependency injection frameworks. The Factory Pattern allows me to abstract the creation of classes from their consumers. This allows the consumed class to be an abstraction, an interface, and allows the management of its creation to be removed as a concern from the consumer. From a testing perspective this allows the injection of mock objects in situations where a consumer of an object is being unit tested and the consumed object has an outside dependency, such as connecting to a database or making a network call. The Factory Pattern also keeps the consumer from being directly coupled to the object it’s consuming. This lesser coupling makes it that much easier to manage changes to the consumed object. If changes to the consumed object do not change the interface the consumer is using, then changes to the consumed object have no effect on the consumer at all.

I use the Singleton Pattern frequently to apply abstraction to objects that do not need to keep state. Static classes cannot implement interfaces, which makes it difficult to mock them when testing their consumers. Singletons allow for a method of applying an interface to what otherwise would be a static class. Using a Singleton instead of a just creating a separate instance for each call to a class allows for more efficient memory management since only one instance to manage, and the interface allows the Singleton to be mocked when and if necessary.

Lately I have used the Mediator Pattern. This pattern became useful in the UI work I have done in the context of event handling. I implemented a Mediator Pattern to create an event aggregator so event handlers and throwers would register and listen and throw events to the event aggregator, instead of directly to each other. This assisted in minimizing memory leaks due to improper releasing of event references , and also decreased coupling of classes needed for direct event relationships.

OnPropertyUpdate Schennanigans

The WPF application I’m working on at the moment has functionality to display multiple chart windows in a main application window page. The chart windows can be resized and moved around inside their window. I wanted to take the resizing and positioning behavior and abstract it so could apply it to other types of child windows besides just charts.

The application structure is based on an MVVM approach so this mean taking the positional pieces of a ‘ChartViewModel’ and abstracting them into a ‘PositionalViewModelBase’ that the ‘ChartViewModel’ and any other view models that would back views that are placed and manipulated on a page would inherit from.

To keep the view models agnostic to their views and to allow positioning change driven by business logic instead of just user interaction, the ‘INotifyPropertyChanged’ interfaced is implemented by the ‘PositionalViewModelBase’ type. What goofed me up was that I had to override the positional properties in the ‘ChartViewModel’ because the ‘ChartViewModel’ data is backed up by a persistence class specific to the ‘ChartViewModel’. I wanted to keep the ‘PropertyChanged’ event code in the base class though, so I came up with the below, using just width as an example:

//--base Positional class behavior.
 public virtual double Width
        {
            get { return this._Width; }
            set
            {
                this._Width = value;
                this.OnPropertyChanged("Width");
                SetParentDirty();
            }
        }


//--chart view model override
 public override double Width
        {
            get
            {
                return this.Model.Width;
            }
            set
            {
                base.Width = value;    //--What turned out to be the issue
                this.Model.Width = value;       
            }
        }

I set the property in the actual data class and the base, I do this so the base can handle setting the parent dirty and firing the changed event. However, I goofed. My chart windows were freaking out when I resized them. After investigating many conspiracy theories and trying to find ways to blame someone else, I realized my error. First I didn’t have any unit tests confirming the behavior, I just assumed it worked.

After adding a unit test I realized that when the property changed event was fired the property showed the old value? The test led me quickly to spot my error. I was setting the base value, and causing property changed event to get fired, before updating the actual data store. Any code fired by the property changed event that wanted the new value, actually got the old one, since I had not updated the data store yet. Dooh!

    
 public override double Width
        {
            get
            {
                return this.Model.Width;
            }
            set
            {
                 this.Model.Width = value;     //--setting data store first fixed problem
                base.Width = value;  
                
            }
        }

The PropertyChanged event driven behavior can be tricky to debug since flow of behavior is not immediately evident. This is why testing it even more important, and hopefully the lesson I have learned here is to test first better. As usual I didn’t save time by not testing adequately, I lost time.

Making UI Notice Change in ObservableCollection Item

I’ve been doing a lot of WPF work lately. I’m getting my head more and more around binding, especially binding to ObservableCollections. It’s interesting how the binding in XAML automagically detects additions and deletions to a collection and updates the UI appropriately. However, I ran into an issue where the update was not to the collection itself, but to item in the collection.

As an example suppose you had the ItemSource of a listbox bound to an ObervableCollection of ‘Coach’ objects.

<ListBox x:Name="lbCoaches"  
                         VerticalAlignment="Stretch" 
                         HorizontalAlignment="Stretch" 
                         DockPanel.Dock="Top"
                         ItemsSource="{Binding Path=Coaches}"
                         SelectedItem="{Binding Path=ActiveCoach}" >
      <ListBox.ItemTemplate>
      <DataTemplate>
            <StackPanel  Orientation="Horizontal">
                <TextBlock Text="{Binding Path=LastName}"></TextBlock>
                <TextBlock Text="{Binding Path=FistName}"></TextBlock>
                <TextBlock Text="{Binding Path=Age}" ></TextBlock>
            </StackPanel>
        </DataTemplate>
       </ListBox.ItemTemplate>
<ListBox>

If you add, or delete, or move a coach in the collection no problem, listbox items are updated. If you change a coaches last name, nothing. I realized that in order to get the binding to update I had to force the UI to know the ObservableCollection updated. I initially tried firing OnPropertyChanged on the collection, but that did not seem to do anything. What I realized what I needed to allow for checks to changes to the items themselves. I could have put a data trigger in place to do this, and I may yet go that route. I think for large lists this is the way to go. For my purposes, since my lists were small, I just cleared and rewrote this lists, hence forcing the UI to realize the collection had changed. Thanks to LINQ I can do this in very few lines.

    //-- coaches is observablecollection backing listbox.
     Coaches[0].LastName = "Thompson";
     var newList = Coaches.ToList();
     Coaches.Clear();
     newList.ForEach(item => Coaches.Add(item));

I think the data trigger is probably the right way to go. The above code will probably confuse people reviewing it and feels like a hack to me. Glad I thought about it, I’ll probably change it now that I was forced to think it through for this post.

Resetting Subversion Solution Binding In Ankh and Visual Studio

Had to reset a solution binding in Visual Studio 2008 after a Subversion repository was changed to use https. We’re using Ankh for Subversion access from Visual Studio.

You would think changing source control bindings would be under File->Subversion->Change Source Control. It’s not.

To change binding roots have to right click on your solution and select Subversion->Switch Solution. Not a big deal, but I spent about 20 minutes running this down. Hope it helps someone.