Naked MVVM – simplest way to do WCF code
How to get testable WCF code in simplest way?
What is the problem?
We all know that creating an instance of service proxy inside of the view model makes writing tests for the view model very hard because during the unit test run we don’t have usually the web service on the other side or even if we do it slows down web tests.
You know how they say
“Unit test is the test which runs without any problem with network cable unplugged”
Like the previous post about simplest possible way to do MVVM, the solution for this problem was covered in so many blog posts that even I am personally aware of a couple of cool and ‘frameworkish’ ways to solve it: use WCF behaviors, create your own ChannelFactory<T> with either sync call in separate thread or IAsyncResult based approach and (my personal favorite) hack the Visual Studio proxy generator. I’m sure there are at least 24 more solutions to do this ![]()
Still, there are two main problems with all the approaches I saw which belong to one of the next two groups:
- They deal purely with async based scenarios.
If I have a service with a method GetForecast(DateTime date), I don’t want to maintain another interface just to get a way to make async call. - They are rocket science type of solutions
We are all geeks and like nice and shiny toys, but what about regular folks like me and a lot of the readers? Is there a really simple way to do this for “us others”?
Luckily, I think I found one which is definitely not the coolest one and 100% can be enhanced etc, but it is the one which proved to me in my day to day WPF/SL coding to be the easiest one “to grok and use”.
Conceptual solution
The solution follows next design goals:
- doesn’t require any typing
- it is using Visual Studio proxy generated with “Add service..” menu action
- it is using the well documented MethodAsync() invoker, MethodCompleted event subscriber pattern
- it is using T4 to auto generate code which enhances the VS generated service proxy
- every service proxy file follows naming convention of ending with word “Proxy”
A year ago, I have blogged in great detail about the unfortunate fact of ServiceClient generated in service proxy not implementing an IServiceClient interface. In case you want to understand what my solution do under the hood go read that blog post now and then continue reading this one. In case “you don’t care how it works as long it is working” here’s a very short summary for you:
ServiceClient generated by proxy generator is marked as partial class.That allows me to create another partial class with same name and namespace outside of proxy which only purpose is to hook the IServiceClient interface I generated manually based on the ServiceClient itself.
In the original blog post I do it manually which ended as a PITA due to the fact that every change of service contract one has to keep updated the interface. As a result of noticing that I waste a lot of time on that, I spent 20 minutes and created a simple T4 class which does that automatically for me.
You can download the source code of end solution here.
Before
Project structure is very trivial. It is vanilla Silverlight project which has a TimerService WCF service doing just this
using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace NakedMVVM.Web
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TimerService
{
[OperationContract]
public string GetTime()
{
return "Yes it works on " + DateTime.Now;
}
}
}
Once we add a service proxy to NMVVM_WCF project (NOTE that proxy name ends with Proxy)
We can happily write now our demoware code “…
namespace NMVVM_WCF
{
using System.ComponentModel;
using System.Runtime.Serialization;
using NMVVM_WCF.TimerServiceProxy;
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
TimerServiceClient client = new TimerServiceClient();
client.GetTimeCompleted += OnGetTimeCompleted;
client.GetTimeAsync();
}
private void OnGetTimeCompleted(object sender, GetTimeCompletedEventArgs e)
{
Message = e.Result;
}
[DataMember]
private string message;
public string Message
{
get
{
return this.message;
}
set
{
if (this.message == value)
{
return;
}
this.message = value;
this.OnPropertyChanged("Message");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Nothing wrong with this code per se, just it makes unit testing of the view model much harder task then it should be…
After
To fix this problem, let’s do next 2 steps:
- download the T4 template file (no need to look in what it contains at all) from here .
- add the file to the root folder of NMVVM_WCF project using VS IDE “Add existing item”
As a result of this activities t4 template was executed and a file with ClientEnhancer was auto-generated with next content
namespace NMVVM_WCF.TimerServiceProxy
{
public partial interface ITimerServiceClient
{
#region Events
event System.EventHandler GetTimeCompleted;
event System.EventHandler OpenCompleted;
event System.EventHandler CloseCompleted;
#endregion Events
#region Methods
void GetTimeAsync();
void GetTimeAsync(object userState);
void OpenAsync();
void OpenAsync(object userState);
void CloseAsync();
void CloseAsync(object userState);
#endregion Methods
}
public partial class TimerServiceClient : ITimerServiceClient
{
}
}
As you can guess, that's complete code I was coding by hand and keep it updated manually with service contract changes. Having this in place it is quite easy to change ViewModel to accept the IServiceClient as a constructor parameter
public MainPageViewModel(ITimerServiceClient client)
{
client.GetTimeCompleted += OnGetTimeCompleted;
client.GetTimeAsync();
}
private void OnGetTimeCompleted(object sender, GetTimeCompletedEventArgs e)
{
Message = e.Result;
}
The only thing left is to update the MainPage.xaml.cs file
namespace NMVVM_WCF
{
using NMVVM_WCF.TimerServiceProxy;
public partial class MainPage
{
public MainPage()
{
InitializeComponent();
DataContext = new MainPageViewModel(new TimerServiceClient());
}
}
}
And that’s it – application works like it was and we have a highly testable view model using only service client interface which is easy to stub/mock.
Having a hard time figuring out path from “before” to “after”? Here’s a short video showing step by step things just described
You can download the source code of end solution here.
Aftermath
My own version of this T4 template, beside the T4 template code used in this blog post is also auto filling IoC container with mappings to all of service clients and its interfaces generated by template. That auto generation combined with auto MVVM wire up I described in first post allow me to have this “TDD enabling of WCF service proxies” fully automated.
I decided not to put that additional template code so it won’t bloat the post with IoC containers etc, but it is VERY easy to modify and customize the T4 template – even if you never did it spend 20 minutes looking at .tt file I shared for this post and I guarantee you – you’ll get it.
The only downside of this approach is that you have to manually drop the T4 template file to every project with service proxies which in my case is not the problem at all – I add it once and after that it keeps things in sync on its own.
I am really not sure why Microsoft is not doing this in the default proxy generation process – it is not breaking anything or damaging backward compatibility and it enables easy testing. I was experimenting modifying the Visual Studio proxy generator myself, but I decided to abandon it (even it was working at the end) due to required registry modifications etc. In my opinion, dropping one file in project without any other requirements to make it testable is more transparent then other approaches and everyone could do this.
What do you think about it? Is it simple enough?
Naked MVVM–simplest possible MVVM approach
How to do MVVM in simplest possible way?
-
No base classes of any kind required for framework
-
No interfaces of any kind required for framework
-
No attributes of any kind required for framework
-
View first – Blend friendly & simple composition
-
IoC enabled
-
Works out of box as much as possible
Basic ideas behind “Naked MVVM”
Scenario
You can download the source code of end solution here.
No base classes, interfaces and attribute
namespace NakedMVVM
{
public partial class MainWindowView
{
public MainWindowView()
{
InitializeComponent();
}
}
}
namespace NakedMVVM
{
public class MainWindowViewModel
{
}
}
Wiring up the view and the view model
namespace NakedMVVM
{
using System.Windows;
public class MainWindowViewModel
{
public MainWindowViewModel(FrameworkElement frameworkElement)
{
frameworkElement.DataContext = this;
}
}
}
namespace NakedMVVM
{
using System.Windows;
using Framework;
public class MainWindowViewModel
{
public MainWindowViewModel()
{
var frameworkElement = ServiceLocator.IoC.Resolve("MainView");
frameworkElement.DataContext = this;
}
}
}
namespace NakedMVVM
{
using System.Windows;
using Framework;
public class MainWindowViewModel : ViewModel
{
}
public abstract class ViewModel
{
public ViewModel()
{
var frameworkElement = ServiceLocator.IoC.Resolve(this.GetType().Name.Replace("Model",""));
frameworkElement.DataContext = this;
}
}
}
Filling the IoC container
using System.Windows;
namespace NakedMVVM
{
using Framework;
public partial class App : Application
{
public App()
{
ServiceLocator.IoC.RegisterType<FrameworkElement,MainWindowView>("MainWindowView");
}
}
}
- I have to do the same thing for every user control/window I have
- I map always framework element to a user control/windows
- The key I use to store it in IoC is the same as the name of user control/window
- every user control is suffixed with “View” and
- every view model of a control is suffixed with “ViewModel”
“Iterate all of the types in current assembly. Each one of them which name ends with “View” map as framework element using the full type name as a key. Each one of them which name ends with a “ViewModel” map as object with a full type name as a key.”
namespace Framework
{
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
public static class IoCBuilder
{
public static void CollectViewAndViewModelMappings()
{
foreach (var type in Assembly.GetCallingAssembly().GetTypes())
{
var typeIsUserControl = type.BaseType == typeof(UserControl);
if (typeIsUserControl)
{
var typeIsView = type.Name.EndsWith("View", StringComparison.InvariantCultureIgnoreCase);
if (typeIsView)
{
ServiceLocator.IoC.RegisterType(typeof(FrameworkElement), type, type.FullName);
}
}
else
{
var typeIsViewModel = type.Name.EndsWith("ViewModel", StringComparison.InvariantCultureIgnoreCase);
if (typeIsViewModel)
{
ServiceLocator.IoC.RegisterType(typeof(object), type, type.FullName);
}
}
}
}
}
}
namespace YAMVVM
{
using System.Windows;
using Framework;
public partial class App : Application
{
public App()
{
IoCBuilder.CollectViewAndViewModelMappings();
}
}
}
My way of wiring up view and view model
namespace Framework.Behaviors
{
using System.Windows;
using System.Windows.Interactivity;
using Framework;
public class AutoWireUpViewModelBehavior : Behavior<UIElement>
{
protected override void OnAttached()
{
base.OnAttached();
var view = (FrameworkElement)this.AssociatedObject;
var viewModelName = string.Format("{0}Model", view.GetType().FullName);
var viewModel = ServiceLocator.IoC.Resolve<object>(viewModelName);
view.DataContext = viewModel;
}
}
}
<i:Interaction.Behaviors>
<Framework:AutoWireUpViewModelBehavior />
</i:Interaction.Behaviors>
Putting it to work
<Window x:Class="NakedMVVM.MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Framework="clr-namespace:Framework.Behaviors;assembly=Framework"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Behaviors>
<Framework:AutoWireUpViewModelBehavior />
</i:Interaction.Behaviors>
<Grid>
<TextBlock Text="{Binding HeadingCaption}" />
</Grid>
</Window>
namespace NakedMVVM
{
using System;
using System.ComponentModel;
public class MainWindowViewModel : INotifyPropertyChanged
{
public MainWindowViewModel()
{
HeadingCaption = "Yes it works on " + DateTime.UtcNow;
}
private string headingCaption;
public string HeadingCaption
{
get { return this.headingCaption; }
set
{
this.headingCaption = value;
this.OnPropertyChanged("HeadingCaption");
}
}
#region The usual INPC implementation
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion }
}
}
Windows LiveID – Microsoft red headed stepchild?
I personally believe Microsoft is missing (if not already missed) the opportunity to monetize serious potential of Windows LiveID.
For years already, there are more then half a billion user accounts (which surpasses current number of Facebook accounts) which Microsoft could’ve use to create serious advertisement revenue the same way Facebook is doing now. The value proposition for users is the fact that they don’t have to remember “yet another user name and password” which is a definite win – at least for me. For identity holder (Microsoft/Facebook), getting information on activities user makes across the web is clearly a win from marketing and advertisement perspective. It is such an obvious case of win-win scenario, that I don’t want to spend any more words on selling it to you, dear reader.
Microsoft (as with many other cool things – Ajax etc) pioneered the Sing sign-on concept more then a decade ago but didn’t do much with it allowing to OpenID, OAuth, Facebook Connect etc to emerge as industry standards.
The reason behind LiveID failure to reach world domination in identity space is related to the poor developer story which prevented wider adoption of the LiveID as “the one online identity”./ Having in mind we are speaking about the Microsoft as developer oriented company I find that to be quite hilarious in one hand and a proof of lack of Microsoft strategic vision in this area. In other words, I believe no one cared(s) in Microsoft so much about getting the benefits from Windows LiveID as some startup might try to (who said Facebook Connect?).
Why Microsoft failed to dominate with Windows LiveID
Here are couple of reasons why I think thinks are like they are right now…
Year 2003, Microsoft attempts rolling out LiveID (at that time called Passport) to couple of big companies (including eBay and Monster) which dies in 2004. Whatever the reasons were, loosing two of such a big adopters in 2004 is (IMHO) VERY stupid because if it did happen I bet we would be all using LiveID across the web right now “with not much of an alternative”.
Year 2006, MS had a STS running on http://sts.labs.live.com. I can not imagine a reason why would something like that die but there’s no such thing today.
Having an STS (web service auth token issuer) is all I would personally care about in order to adopt LiveID in my apps.
On Mix 2008, they announced Windows LiveID SDK CTP which was up until yesterday the only way of integrating Windows LiveID with client apps and sites. They have also announced on the same mix that LiveID would become OpenID provider, but that didn’t long last too.
Beside this efforts, Microsoft was trying also to pitch LiveID in parallel using its own strongest weapon: Windows.
Microsoft's Windows XP has an option to link a Windows user account with a Windows Live ID (appearing with its former names), logging users into Windows Live ID whenever they log into Windows. To me that sounds very nice (I’ve already auth myself logging on my PC and established a trust relationship which for most of the web sites out there should be sufficient). The only problems with this is that is almost unknown feature. I did a smoke test asking 10 people I know which use Windows Live Messenger on day to day basis if they use it – none of them even knew about it. I don’t even have clear understanding how this thing gets installed other then guessing it gets bundled in Live essentials installer .
Then, there is CardSpace which is industry correct and secure way of handling our online identity information. All great, except for the fact that it is quite a mystery “how to use it”
. In 2007, there was a beta of CardSpace LiveID integration but after that nothing happens.CardSpace being a part of most of Windows apps is such a untapped potential that it is hart for me to believe that no one is trying to utilize it more seriously.
Couple of things I hope Microsoft will do with LiveID in the future
Microsoft still has some chance to emerge as one of the leaders in identity space but to do that they might consider doing some of the next things:
- promote “LiveID” to become a 1st grade citizen in Windows.
Ask for LiveID to be entered during the windows installation process (most of us have it anyhow). Windows Live service would then (during the install process itself) issue Card Space managed card for a user. Right from the moment system would be installed, that card should be used on every LiveID site.
Even better put that card on my Live SkyDrive so it could roam with me while I work on different computers. If not possible to be built in Windows (ether Win7 SP1 or Win8), can we at least consider building it in Internet Explorer 9?I know this could be probably breaking some monopoly law, but lets face it – MS didn’t become what it is playing fair but playing bold.
Apple integrating MobileMe and Chrome integrating google bookmarks and Flash are doing exactly that. - Use LiveID on ALL of the Microsoft sites. No excuses. Period.
Just check out last post on windowsteamblog.com which (ironic isn’t it) introduces newest LiveID “Messenger Connect” API.
To post a comment you need to Sign In
but that is not using the LiveID
If you don’t trust in it, why should we?
- Spread it across the web similar to Facebook ‘Like’ button (‘Post with Messenger’)
Here’s a sample of how Bing can be used to collect ‘Likes’ by adding a ‘Post With Messenger button’ which would send it to people on messenger contact list andor Facebook, MySpace etc… Even this would end with forwarding it to Facebook as ‘Like’ there is still value in collecting those data associated with LiveID…
.png)
Do the same with as much as possible social networking sites.
Aggregate the data and share it with us developers so we can personalize better our content (not only ads)..
- Stay away from hustling users as much as you can
Force me to log in only once in 24 hour or more. I ‘m sure this goes against best security practices etc. but for most web sites it really doesn’t matter. Otherwise you shift from "login screen” to “nag screen“ - Support other browsers the same you do with IE.
What’s the story with the FireFox and Windows Live? One of my friends, decided to use DropBox instead of LiveMesh (even offered 250% more storage space) just because he hates LiveID. Reason: he uses Firefox and it looks like that “Remember me”check box on Firefox has slight dementia so the login screen is quite annoying
- Support other security protocols
LiveID as OpenID provider, OAuth etc… The more adapters the merrier.
Last but not the least - respect us developers
I got personally interested in this topic because I choose WPF for my LOB application I am playing lately and I decided to use LiveID for authentication (everyone I know has one – regardless how they use it).
My preferred approach to building this app is S+S (which I am not sure if is still official MS way to go) where a desktop client application gets powered by services from the web/cloud getting with this approach best of both worlds: best user experience on windows machines + data in the cloud.
I was so naïve when I decided to try tout LiveID to expect to find some LiveID STS web service to which I would pass user name + password + ApplicationID and get back in response membership token. Naïve because I didn’t even consider the possibility that such thing doesn’t exist which ended as a true case.I really don’t understand why there is no such offering by Microsoft as we speak.
The second in favor solution is “acceptable” experience Microsoft has in its own Live Essential suite tools.Here’s a sample of how to do it.
As you can see it is a simple client app window which I am not sure what it does on “Sign in” but whatever it does (POST or web service) I am ok with using it too.
What I don’t want:
- login control being a web browser control showing the special windows live login html page
- generic control where I can not change the text (my app + folks not speaking English)
Reasons why I don’t accept those two things are I guess exactly the same as the one Microsoft came up with when deciding not to use it in their own products.
If Microsoft expects me to use LiveID in my WPF apps they have to provide me a way to get the same user experience they have in dealing with the same problem.
Yesterday Microsoft released new Messenger Connect SDK which contains a sample WPF application and WPF template which is encouraging. In order to run the sample, one need to register application with windows live which right now is done through connect where you fill the request form and someone sometime would consider it.
Based on a quick glance over the sample there are no obvious ”skinning” capabilities – no control just a direct call to some function. The only thing I could do while waiting (hopefully) to get an LiveID was to run the sample as it is out of the b ox and this is the result I got “HTML in a box” – not very encouraging.
I’ll wait for the application key before I make a final call but so far it doesn’t look like Microsoft cares about WPF + LiveID integration experience..
Keeping fingers crossed but not holding my breath …
5 reasons why Silverlight sucks in LOB (compared to WPF)
Recently, Brian Noyes and Rob Relyea have touched the “WPF VS Silverlight” subject and considering the fact I was also recently thinking about it I wanted to share my thoughts on that topic too.
As I said in previous post, I’ve started at home blogging about the accountingLOB applications in Serbia and one of the questions I got challenged by one of my readers (who knows how BIG Silverlight fan I am) is
“Would you be using Silverlight for your own accountingLOB application?”
Initially answer looked very clear to me: with all the improvements Silverlight 4 brought to LOB game, desktop like programming model and web deployment looks like a perfect fit for public facing application (outside of intranets)
But, after doing some more thinking on this subject, to my surprise I came up with the opposite conclusion:
WPF is better choice for serious LOB applications.
And here are 5 most important reasons why I think like this:
Silverlight 4 is not cross platform environment any more
The biggest advantage SL had over the WPF (in my mind at least) is ability to be deployed to non-windows machines (MacOS and Linux powered machines).
Having Silverlight 4 with a whole slew of COM+ dependable features virtually prevents creating a Silverlight 4 siteapplication which would run on Mac and Linux. At least, that is the state as of today I am aware – somebody please correct me if I am wrong in this.
The way I see this change is that Silverlight 4 is shifting toward being unique “cross-screen” (desktop, mobile and TV) platform which is perfectly fine with me just it doesn’t have any particular value in context of LOB applications).
UPDATE: I did found a couple of folks with Mac which were kind enough to tell me that on Silverlight.net site there is Silverlight 4 plug-in for Mac which (as long as COM+ features are not used) works fine.
Silverlight adoption rate is not good enough
According to later RIA Stats adoption rate of Silverlight is around 60%. I’ll put aside the fact that I am not seeing that number around me in Czech Republic and accept it as correct one with slightly different interpretation: 40% of PCs are not having Silverlight installed.
The funniest thing is that WPF has 99% adoption rate because every PC with Windows newer then Windows XP SP2 (including Vista and Windows 7) has WPF installed on it. I am not sure how many Windows 2000 and Windows 98 machines are out there but whatever the number that is personally I don’t think anyone should care targeting that segment as very unlikely to invest any money in purchasing your LOB product.
Even if a PC is not having the .NET framework at all, the download size to get it on PC is just 28 MB which is bigger then 9 Mb size of MacOs Silverlight 3 plug in but who cares (with any non dial up connection it is matter of seconds). In my personal opinion, this is one of the most important WPF features in .NET 4
Silverlight tooling is good enough. WPF tooling is better
Starting with VS 2010 and Blend 4 we can work in SL4 and Silverlight is getting much more attention (just look at the paces of silverlight and wpf toolkits and everything gets to be clear there) but using WPF allows me to use all of the memory profilers, dbg viewers, any framework I want etc. If you are in doubt what exactly I think with this here’s an example: Silverlight does support printing but in case of serious LOB applications you need all the muscle WPF offers. Think something like Crystal Reports for example.
Silverlight programming model is more constrained then the WPF one
Doing Silverlight applications, one is forced to adopt the “make async web service call and get a chunk of data and do something with it” which in my personal experience limits the productivity of LOB developer compared to the speed he has developing with WPF . There’s no direct access to DB (which is actually great) but that ignores the fact that some LOB applications might need just that. For example, application can be written to target local SQL CompactExpress which then is set up to replicatemerge deltas with the central enterprise server. Anything like that (and we know how this things can get crazy in enterprises) is not possible in Silverlight.
Another thing related to this is aspect of offline access. I am aware that Silverlight 4 does have isolated storage and yes it has a bunch of open source DBs sitting on top of it, but it is just a single user storage. In reality, quite often in serious LOB applications we are seeing office andor P2P network topologies where it is essential that you have a “proxy per office” or ability to sync directly the data of “user X”. I know that Sync Framework is coming for Silverlight in 2010 but it is not there now and I am not sure if it would support topologies other then client <->(Azure) server.
Silverlight is still technically inferior to WPF in some areas.
Read Brian's post to see what this point is about.
Conclusion
Now you heard 5 of my most important reasons why I choose to stick with WPF on this. Am I missing the point? Making a false statement? Do you have more reasons in favor of WPF or Silverlight?
Looking forward to hear the comments
Me, myself and design patterns
Looks like the Silverlight related posts I’ve announced would have to wait one more blog post due to the event which happened to me today and which made me thinking about a few of the architecture related things which at the end resulted with a few of (at least for me) interesting thought I felt sharing with the community.
The event
So, a fellow blogger @RadenkoZec made a nice blog post about Facade design pattern in which comments we had a discussion if the example is appropriate or not, and if the implementation is Facade design pattern or some other pattern. I won’t repeat here in detail what we were discussed there (go to the blog post to read comments) but there were couple of things in that discussion I was thinking about during the evening…
Patterns should be explored in 3D
It is very interesting that the sites on the net (like the dotfactory.com) seems to be primarily focused on GoF patterns while I was not able to find sites covering at the same time PoEAA patterns andor DDD patterns.
That fact might look irrelevant but if you would check out the content of today’s discussion you would se that the same example code used in blog post
looked to Radenko as Facade (GoF)
and to me more like a Gateway (PoEEA)
If you just take a look at above pictures, you would find for sure at least some similarity and that’s why one should look at all of the patterns in whole and not just be exclusive in picking “The book”. Another example of this interpretation conflict can be found between the PoEAA and DDD where patterns such as repository, factory etc some times have different usages if not different meanings.
In other words, IMHO every developer should persist knowledge in three dimensions:
- X– DDD, PoEAA, GoF
- Y – specific patterns and their implementations, implications; anti patterns too.
- Z – time
For the ones of you probably asking what time has to do with this subject - here’s an answer. Software landscape changes significantly in last 20 years so some of the “scriptures” should be taken with a grain of salt.
Here are couple of examples illustrating my point:
- Observer pattern doesn’t have a lot of sense being implemented out of box with .NET events,
- Singletons (btw, would have a dedicated post showing how evil they are) are kind of obsolete with the usage of the IoC containers etc
Another aspect of the need for considering the time dimension in design patterns exploration is the fact that in last few years we are all witnessing both the rise of the dynamic languages and the enhancement of static languages where they are getting aspects not existing in the time when “pattern Bibles” were made (lambdas, generics, C# 4.0 dynamic etc). Every of the patterns therefore should be heretically challenged in the lieu of current state of technology.
Context is the king
By mare looking at above diagrams (which for my point can be both pure UML diagrams) it would be really hard to tell what is the difference..
In both cases we have multiple classes encapsulated in one class orchestrates their calls and expose simple API to be consumed.
But if you take a look at the context you can see based on the provided code sample that the packages in case of facade are interconnected, each one of their classes is dependable in it’s own way dependable on other classes and none of them can exist without others. I could imagine refactoring merging those 3 classes in one. In other words, even physically we have multiple classes caring their own implementation they are so connected that on architectural level there’s just one entity which is hiding behind the facade.
That’s why for me Facade feels like “1 – 1” relationship type pattern where a facade hides the complexity of the class (similar in a way to adapter but let’s not digress with that here)
The second case is with clearly different context where all of the packages behind the “facade” (Gateway) are quite independent. They do not depend on each other at all, they cooperate as partners.
The purpose of the PricingGateway is also to expose a simple API to pricing Package but this time when the API would be used Gateway would perform a role of a conductor, orchestrating the calls to the "hided" elements.
That’s why for me Gateway fells more like a “1 – n” relationship type design pattern
To summarize: In order to distinct patterns one would have to understand the problemimplementation context before picking the right flavor – appropriate pattern.
Patterns as a matter of feelings
As you have probably noticed in the text above I am using the “feels like to me” which I’m pretty sure is looking quite unrelated to explicit and scientific thing such are the design patterns so let me clarify that for you
As many other, I’ve stepped through couple of phases in my Pattern life
- Discovery of patterns (we hear about them from some of the cool kids and all we do at this stage is trying to pretend as best as we can to look like we know what they are talking about)
- Trying to get it (AKA “I foundread the GoF book”)
- Becoming a believer (including making the presentations to people in phase #1)
- Getting it for real (reading every patterns book, blog post etc you can find and memorizing the UML diagrams, use cases etc)
- Seeing patterns everywhere and doing them as much as we can
- Paying the price from highly complex code base .
- Starting to understand the price of patterns application and start using it only when a real design pain is identified which can not be solved on simpler (but still clean) solution
- Instead of patterns catalogs starting to focus on basic principles.
So, as far I can tell I am in that phase #8 where all of the patterns somehow melted with each other and all of them “look similar”. I forgot half of their UML diagrams and reference implementations. The only thing in my head left is the name of the pattern, notion of the use case when it is useful and (very blurry for most of them) how it works.
Reading my last statement someone could make a conclusion that I just got more stupid (possible option I admit
) and to lazy to remember things but I would disagree with him because every one of the patterns I faced is based on the same set of plain logic principles which in case you know and feel them you are good to go with doing “your own” solution which would somehow match some of the patterns.
Here are some of examples of the design principles I have on my mind: SOLID, open-close, DRY, KISS, orthogonal code, OOP principles (encapsulation, abstraction), TDD, dependency injection and the list could go on with pages
To summarize: I strongly believe that if the developer is feeling natural regarding the design principles (spits out the code following those principles without even thinking) the knowledge of the design pattern can be at much more abstract level (in a way like knowing a page index of a book) without memorizing every bit of their reference implementation (that’s why we have bing aren’t we?) and the created code would still comply to all of those patterns.
Conclusion
I hope all of my rumblings I shared with you my dear reader would help me now to make up the point of this blog post and that is to explain how come when Radenko pulled (completely rightfully) on his blog post couple of referent examples from sites and books of folks far smarter then I am proving that his example implementation is the same as the one they provided, the only thing I could tell him is that his example “doesn’t feel like a case for Facade to me”.
I was not claiming neither that the guy who wrote a book did it wrong nor that the dotfactory.com site got it wrong in their sample.
It was just a gut filling of a pragmatic “duct tape architect” which I would have about that code if it would be mine which I shared with him and the community.
Design for testability – WCF proxies
Recently I spent some time participating in projects involving Silverlight, Prism etc and there are couple of interesting things I’ve came up with during that period which I would like to share with the community in a form of a couple of blog posts showing the “enhancements” I did in our Prism based implementation.
I was thinking a lot where to start and as a result of that I have decided to start with something small but useful. I’ll focus in this blog post on Silverlight, but this simple trick is usable in any other client technology making WCF calls. So, here we go…
How to have testable Silverlight code depending on WCF calls
Why reinventing the wheel?
In order to make sure that trivial thing I’ll be writing about today was not already covered by someone I did my Bing homework and came out with two approaches you might want to check out:
- Derik Whittaker adapter based solution Abstracting away Dependencies for Simpler code
- Fake host based solution http://www.silverlightshow.net/items/Deep-dive-into-WCF-part-1-TDD.aspx
While I find both of them to be perfectly acceptable solution I think they are suboptimal due to different reasons.
In case of first solution (which based on screen cast comments is the way a lot of people do) there is one more layer of abstraction to be maintained.
In typical DDD style application we have DB tables mapped to domain entities which are (usually) flattened in web server layer where the WCF service contracts behave as application level services with client centric shapes and behaviors. With this approach we need another interface with either its own behaviors or just copy pasting the service contract and additional adapter class which delegates the calls to proxy. IMHO, layer of abstraction down –> maintainability level up
In case of second solution, my objections are similar to the one I have regarding service locator. Abstracting the “locator” (servicehost) leads to opaque dependencies on a consumer level which are much harder to be unit tested and understood. On top of that, I find this solution also to introduce additional complexity with defining factories, providers etc is IMHO are overkill for simple “TDD enable WCF proxy dependable code”
Duct tape programmer solution
Regardless of how much I disagree with Joel on the value of the duct tape programmer, I couldn’t get away from the fact that my solution compared with other two (full of big patterns and cool code) looks exactly like it is been done by the duct tape programmer – me.
That’s ok, simplicity is #1 design criteria for me.
In this solution I won’t be using therefore any patterns but instead I would just rely on one hack and one small convention to get quickly testable code which is easier to be maintained and understood (compared to other approaches).
Demoware “WCF proxy being called directly” sample
So, here’s the setup for today post. We are having application which goal is to show the names of the users having salary greater then $1000.
Client is implemented using Silverlight accessing the user data on a server side by making a WCF service calls.
In order to do that I used vanilla Silverlight solution (didn’t want to use Prism here) consisting of two projects:
- Web application containing a UserService.svc WCF service and hosting a silverlight app.
- Silverlight application which has UserService service proxy and MainPage showing the names of users in a ListBox.
UserService.svc
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace SilverlightApplication.Web
{
[ServiceContract(Namespace = "http://blog.vuscode.com/200911")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class UserService
{
[OperationContract]
public Collection<User> GetUsers()
{
return new Collection()
{
new User { Id = 1, Name = "Nikola", Salary = 1000 },
new User { Id = 2, Name = "John", Salary = 2000 },
new User { Id = 3, Name = "Jane", Salary = 3000 },
};
}
}
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal Salary { get; set; }
}
}
Nothing important here: In one file OperationContract defining a method GetUsers returning the collection of users (User DataContratct being defined in the same file)
Let’s move on…
MainPagePresenter? Where’s the MainPageViewModel?
Well, I was surprised that many people I spoke with recently think MVVM is not the only “right” way to do SilverlightWPF development and I tend to disagree with that. While MVVM has its own values (it is also presentation pattern of my choice too) you can do MVC or MVP (both passive view and supervising controller) equally successfully like you can do it in desktop applications (speaking of which, Silverlight for me is desktop app deployed through browser) If you don’t trust me, ask Jeremy. That’s why I ended with some implementation for this
So, in order to spice up this blog post a bit I ended with MVP- like implementation with MainPagePresenter implemented like this
using System.Windows;
using SilverlightApplication.UserServiceProxy;
using System.Linq;
namespace SilverlightApplication
{
public class MainPagePresenter
{
private FrameworkElement view;
public MainPagePresenter(FrameworkElement view)
{
this.view = view;
}
public void Init()
{
UserServiceClient proxy = new UserServiceClient();
proxy.GetUsersCompleted += (sender, e) =>
{
this.view.DataContext = e.Result.Where(p => p.Salary > 1000);
};
proxy.GetUsersAsync();
}
}
}
Constructor here is more interesting because it accepts the instance with type inheriting from FrameworkElement (pretty much most of controls in Silverlight) and stores its pointer to a view filed. In other words, abstraction of a view is being injected into the presenter just instead of the IView I am being smart here and using the FrameworkElement as abstraction every view (user control implements).
It is the good old demoware type of code you’ve seen on a lot of places with proxy being instantiated in the method body spiced up with cool lambda implementation of async event handler (which any better presenter would use to scare the session attendees) and with a simple linq statement filtering the result set to exclude the rows lower then 1000.
The magic in this code starts when view FrameworkElement.DataContext gets set by the filtered result set. Presenter doesn’t have a clue about what specific control view is but still it is able to set its common property to a value generating desired view behavior.
Wiring up the view and the presenter
There’s really big religious war on the IT sky regarding who is created first (view or viewmodel presenter) and the allowed level of coupling between them. I have my own take on that to which I would dedicate a separate blog post (it is important subject) but for the sake of this blog post let say that it is perfectlly fine that view is created first and that it has direct reference to presenter.
That’s how the view (MainPage.xaml file) ended being implemented like this
using System.Windows;
using System.Windows.Controls;
namespace SilverlightApplication
{
public partial class MainPage : UserControl
{
MainPagePresenter presenter;
public MainPage()
{
InitializeComponent();
this.presenter = new MainPagePresenter(this);
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.presenter.Init();
}
}
}
As you can see in a page constructor a instance of the presenter was created with a pointer to the page itself being passed to presenter (which if you look up would be held as a presenter field and used in Init method).
Then Loaded event handler is being created (don’t put any UI related code in the constructor because it is not guaranteed that UI would be ready when that line would be executed) and in it presenter.Init() method invoked. In other word, view said to presenter “Please set me up!”
Markup code
Did I tell you how much I like WpfSilverlight? Check the simplicity of the markup code!
<Grid x:Name="LayoutRoot" Background="White">
<ListBox
Name="listBox1"
ItemsSource="{Binding}"
DisplayMemberPath="Name" />
</Grid>
Setting ItemsSource to {Binding} effectively said to control “Bind to your own DataContext” (key moment specific to WPFSL), and DisplayMemeberPath Name value can be read “whatever the collection would be in DataContext, collection item would have a property called Name”
Simple, elegant and powerful!
Runtime experience
Wow, so much talk about such a simple thing. Ok, I proved it working
My duct tape based solution
is based on the simplest possible solution I was expecting that WCF supports out of box: IXYZServiceClient interface contracting in abstract way proxy behavior.
To my surprise I have realized that WCF generated proxy is not creating that interface (IUserServiceClient in this example) so I decided to created in manually.
Doing things WCF team should have already done
I’ve clicked on Show All files icon (to see hidden proxy files) and opened Reference.cs file containing proxy c# code.
Then I found UserServiceClient class definition
Right click it and pick to extract interface (R# can help with this too)
I pick only the members I care to be abstracted (leaving unchecked all of the WCF infrastructure members)
and ended with this
Obviously not good solution because next proxy refresh and all this is gone, so there are two problems:
- How to preserve interface
- How to avoid having manually to add interface implementation to generated ServiceClient class.
In order to solve problem #1, I have created then a folder with the same name as the proxy and drag and drop the interface to that folder. First problem solved!
In order to solve problem #2, I am utilizing the fact that the ServiceClient is generated as partial class so I create in the new folder another partial UserServiceClient class implementing the IUserServiceClient interface. Here’s how that class look like
namespace SilverlightApplication.UserServiceProxy
{
public partial class UserServiceClient : IUserServiceClient
{
}
}
I hope now you can get the reason why I was a folder with the same name as the proxy –> the namespaces of types and interfaces in that folder are matching out of the box the ones in the proxy class
And here's the solution (for visual learners like me)
To summarize the solution:
- I’ve created the IServiceClient by simple extracting the facade of the proxy client interface
- I’ve created partial UserServiceClient which is only attaching the interface to proxy
- Both of files are not destroyed with proxy regeneration.
- If the WCF service contract changes over the time, regenerating of new IUserServiceClient is trivial task taking less then 15 seconds.
Duct tape solution at its best!
Modifying presenter
using System.Windows;
using SilverlightApplication.UserServiceProxy;
using System.Linq;
namespace SilverlightApplication
{
public class MainPagePresenter
{
private FrameworkElement view;
private IUserServiceClient userServiceClient;
public MainPagePresenter(FrameworkElement view, IUserServiceClient userServiceClient)
{
this.view = view;
this.userServiceClient = userServiceClient;
}
public void Init()
{
this.userServiceClient.GetUsersCompleted += (sender, e) =>
{
this.view.DataContext = e.Result.Where(p => p.Salary > 1000);
};
this.userServiceClient.GetUsersAsync();
}
}
}
As you can tell I’ve made two changes:
- added another parameter to the constructor injecting the newly created IUserServiceClient interface
- Modified Init method to replace proxy instantiation with usage of injected client proxy abstraction.
Modifying the view
Usually I wouldn’t modify the view but instead rely on IoC container to inject the UserServiceClient instance, but in order to keep this post focused I won’t be using IoC here (you’ll see it in one of my future posts showing my Prism enhancements) so I needed to make a simple change in a page constructor
public MainPage()
{
InitializeComponent();
this.presenter = new MainPagePresenter(this, new UserServiceClient());
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
Nothing special, just added new UserServiceClient() to the parameters being passed to a presenter.
Running the app again
Yeap, still works
Where’s the unit test?
Well, this blog post is long enough (and it is late enough
) so I would skip the unit test example this time because it is fairly trivial to be written now when we have interface of the service proxy.
Summary
In this blog post I showed another way how to easy introduce a layer of simple abstraction between the WCF service proxy and the code consuming it.
I find the advantage of my approach VS the two of others in its simplicity and maintainability but again considering I “invented it” that comes as no surprise to me
Source code of the end solution can be downloaded from here.
Say no to ServiceLocator
(Disclaimer: As I stated here, while I find over the time ServiceLocator based code to be a bad practice, I do understand the need for its usage in certain brown-field scenarios as a way of reducing the risk while introducing the IoC.)
In my previous Nikola’s laws of dependency injection blog post I stated couple of IoC laws based on my experience:
- Store in IoC container only services. Do not store any entities.
- Any class having more than 3 dependencies should be questioned for SRP violation
- Every dependency of the class has to be presented in a transparent manner in a class constructor.
- Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies.
- IoC container should be explicitly used only in Bootstrapper.
Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container.
The #5 (“IoC container should be a ghost even in unit tests”) resulted with couple of blog post comments and emails asking for clarification what I mean by that.
In short:
Say no to Service Locator Opaque dependencies!
Radenko Zec posted in comment example which with very slight modifications (to reflect better my Law #1) looks like this…
There are 4 projects in the solution used in today blog post:
- ClassLibrary containing the two classes where:
- UserRepository is having dependency on other
- LoggingService (implementing the ILoggingService) - ConsoleApplication1 simulating the production usage and containing the:
- bootstrapper class (defining IoC mappings) and the
- Program.cs (main console file which would execute our functionality - Infrastructure containing my naive implementation of Unity container adapter with the
- IContainer abstraction of the Unity container,
- UnityContainerAdapter class implementing the adapter design pattern adapting the UnityContainer to IContainer
- UnityContainer service locator class, - TestProject1 containing the unit test for the ClassClibrary1 - UserRepositoryTest
Before diving into the Radenko’s sample implementation let me restate my point by saying that
- none of the classes using IoC (in this simple example UserRepository) should NOT be aware at all of IoC and
- UserRepositoryTest should NOT have testfixture setup methods filling the container
Service locator based implementation
As given in Radenko’s comment example Bootstrapper class registers the mappings
namespace ConsoleApplication1
{
using ClassLibrary1;
using Infrastructure;
public static class Bootstraper
{
public static void SetUp()
{
IContainer cont = UnityContainer.Instance();
cont.Register<ILoggingService, Loggingservice>();
}
}
}
Here’s the simple implementation of that LoggingService (not very important for this blog post but still to be clear)
namespace ClassLibrary1
{
using System;
using System.Diagnostics;
public class LoggingService : ILoggingService
{
public void Log(string message)
{
Debug.WriteLine(string.Format("LOGGED: {0}.", message));
}
}
}
And here’s the class being dependable on that LoggingService
namespace ClassLibrary1
{
using Infrastructure;
public class UserRepository
{
public void Delete (int userId)
{
IContainer cont = UnityContainer.Instance();
ILoggingService loggingService = cont.Resolve<ILoggingService>();
loggingService.Log(string.Format("User with id:{0} deleted", userId));
}
}
}
So, as you can see in a given example Delete method is implemented like this:
- get ServiceLocator (singleton instance of the UnityContainerAdapter)
- using the ServiceLocator retrieve from IoC container component mapped to ILoggingService
- use that component to log a message.
What is wrong with this code?
- It violates the Separation of Concerns Single Responsibility Principle – UserRepository taking care about IoC, instance resolution etc
- It good example of opaque dependency injection which hides sometime the set of dependencies component has.
Looks like “not a big deal” but when you face the class with couple of thousands of lines and you have to read them ALL just to get the list and repeat that couple of times, it is a big deal. (Yes, I do agree with you that having that long classes is atrocity of its own kind, but seeing it all the time in my world)
(Couple of more reasons but let’s just continue our journey…)
Here’s how the production usage would look in this example
namespace ConsoleApplication1
{
using ClassLibrary1;
class Program
{
static void Main(string[] args)
{
Bootstraper.SetUp();
UserRepository userRepository = new UserRepository();
userRepository.Delete(3);
}
}
}
No magic there: code issues a command to bootstrapper to initialize IoC, create a instance of UserRepository and invoke its Delete method.
The last thing left is the example of unit test one might write with this code
namespace TestProject1
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ClassLibrary1;
using Infrastructure;
using Rhino.Mocks;
[TestClass]
public class UserRepositoryTest
{
private ILoggingService loggingService;
[TestInitialize]
public void Would_Be_Executed_Before_Every_Test()
{
var serviceLocator = UnityContainer.Instance();
loggingService = MockRepository.GenerateMock<ILoggingService>();
serviceLocator.Register(loggingService);
}
[TestMethod]
public void Delete_InCaseOfValidUserID_WouldLoggAMessage()
{
// arrange
var userId = 3;
loggingService.Expect(p => p.Log(string.Empty)).IgnoreArguments();
// act
UserRepository userRepository = new UserRepository();
userRepository.Delete(userId);
// assert
this.loggingService.VerifyAllExpectations();
}
}
}
This is not a blog post on unit testing so just a short discussion what the test does :
In Test initialization the singleton instance of IoC containe is retrieved. Then an RhinoMock dynamic mock class of ILoggingService is created and then injected into the container. Summarized: we stored something in a container before the test execution, because we know from the source code that it would be used in SUT.
The test itself is very simple:
- Arrange defines what is the expected behavior of the logging service which is supposed to be caused as a result of SUT activity
- Act creates an instance of the UserRepository and invokes the delete method
- Arrange verifies that the expected behavior of the logging service occurred.
Nothing much –> just another example of behavior unit testing.
What is wrong with this unit test?
Well, I wrote them “a few” like this and it works well but with certain pain points which the more test you write the more painful become:
- It prevents black box unit testing.
I tend lately to think about unit tests more as of a functional specifications and due to that I try always to test the class based on defined functional requirements WITHOUT looking in the implementation (to stay as objective as I can). Only once I cover ALL functional cases, I tend to do a quick check of the test coverage and focus on removing the code not being tested (all reqs satisfied and code not used –> potential overkill) - Prevents effective unit testing
Sooner or later, with this code you end with writing test following the “run the test, get what is missing, add a mapping, run it again, get what is missing, add a line…” which IMHO ends to be very slow process. - Makes Fixture'SetUp very big and clunky.
Here we set up one dependency, but imagine hundreds of unit tests with their own many dependencies dig up in the code and how big this section would become…In the past I was trying to tackle that by creating special bootstrapper classes filling the IoC container with test infrastructure stubs and with using AutoMockingContainer (still not completely sure about should I do that or not – another blog post) but the end result is that I got more code to be maintained and which is getting broken wevery time production interfaces change etc.
- Decreases test readability
If you want take tests as a sort of functional specification (and you should) pretty often you would want to “read the tests” in order to get what and how the SUT works. Having a bunch of setup code outside of the method being read makes that much harder.
All the right solutions are always simple as possible
In order to comply to law #5 I need to refactor the UserRepository implementation by removing IoC container from it and in order to comply law #3 I need to explicitly enlist in a constructor all of its dependencies.
So, following those two rules I end with this code:
namespace ClassLibrary1
{
public class UserRepository
{
private readonly ILoggingService loggingService;
public UserRepository(ILoggingService loggingService)
{
this.loggingService = loggingService;
}
public void Delete (int userId)
{
this.loggingService.Log(string.Format("User with id:{0} deleted", userId));
}
}
}
As you can see all I did was to transform the ServiceLocator type of code to dependency injection type of code where there is no more SoCSRP violation and where the UserRepository is unaware of IoC (no single line related to it).
For the folks with concerns that this could result with some very long constructors with too many dependencies I suggest checking out Auto Mocking Container and/or:
Law #2 Any class having more than 3 dependencies should be questioned for SRP violation
Let see the unit test for this class
namespace TestProject1
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ClassLibrary1;
using Rhino.Mocks;
[TestClass]
public class UserRepositoryTest
{
[TestMethod]
public void Delete_InCaseOfValidUserID_WouldLoggAMessage()
{
// arrange
var userId = 3;
var loggingService = MockRepository.GenerateMock<ILoggingService>();
loggingService.Expect(p => p.Log(string.Empty)).IgnoreArguments();
// act
UserRepository userRepository = new UserRepository(loggingService);
userRepository.Delete(userId);
// assert
loggingService.VerifyAllExpectations();
}
}
}
As you can see above:
- There is no more initialization routine – all of the code related to this test is in one place.
- Every test initialize only what it needs (no big chunk of initializing union of of mappings all tests need)
- While writing the test the C# compiler informs me that the UserRepository needs a logging service. If I don’t provide it test won’t compile.
That’s how I can avoid looking at the source code in order to get what dependency class has, - As for law #5, notice that in my unit test there is NO IoC code at all (even infrastructure component is not referenced anymore).
IoC has to be for us when needed but also it has to stay away from our work. Full orthogonality. Period.
How the production code looks with new approach?
Almost the same
namespace ConsoleApplication1
{
using ClassLibrary1;
using Infrastructure;
class Program
{
static void Main(string[] args)
{
Bootstraper.SetUp();
var unityContainer = UnityContainer.Instance();
var userRepository = unityContainer.Resolve<UserRepository>();
userRepository.Delete(3);
}
}
}
The main difference is that I’ve used the unity to resolve UserRepository and performs (by that) automatic object graph wire up. It may look like that we ended with the same thing just in other class and that is correct (partially)!
It is correct in a sense that if you think for a second about the real world systems you have many classes chained in cross dependencies in which case it is in your interest to push out from all of them the IoC resolution and let the IoC container of your choice do the auto wire up magic.
It is not correct in a sense that in a most part of your system (usually matching the area you want to test( you what have implict injection and not this explicit. For example, if your CompanyRepository would need a UserRepository (not claiming it has real sense to be done) the CompanyRepository would just have in its constructor IUserRepositoryUserRepository and that’s it.
Conclusion
Reafactoring from service locator to real dependency injection type of code is very easy if not trivial but do require a small “bing!” in your head to just realize it.
After switching to this practice, my tests get much lighter, faster, easier to read and maintain.
Radenko, I hope I answered your question
Here’s a sample code I used in today’s blog
Inversion Of Control, Single Responsibility Principle and Nikola’s laws of dependency injection
Today I stumbled upon the stack overflow question regarding using DI frameworks for classes with many dependencies where the example given and couple of answers have reminded me about a subject I want to post for a long time.
So the example from question basically goes like this:
MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)
// ... versus ...
ILog log = DIContainer.Get<ILog>();
And the 3 questions related to this example are:
- How to avoid passing those common but uninteresting dependencies interfaces to every class?
- How do you approach dependencies that might be used, but may be expensive to create?
- How to build object graph of MyClass considering the fact that any of those dependencies can have their own dependencies etc..
So, let’s start and keep it short…
What is wrong fundamentally with his example?
Being a big proponent of DDD principles as the one leading to clean and maintainable design, I found the design of the question example is wrong in a sense that an entity (which MyClass is) should NOT have dependencies on infrastructure (or any other) services.
Related to that is Nikola’s 1st law of IoC
Store in IoC container only services. Do not store any entities.
I strongly believe that if the author of example was following that principle he wouldn’t be in the position to ask the question he did ask.
Second thing I learned in past years to detect as wrong in code like the one in example is the high number of dependencies in a constructor which usually in my experience points to SRP (Single Responsibility Principle) violations and low SOC (Separation of Concerns) in code. The example is not showing the code of the MyClass but (based on my experience) I am pretty sure it can be broken to couple of coherent SRP separate classes where each one of them would have very few (if any) number of dependencies
Related to that is Nikola’s 2nd law of IoC
"Any class having more then 3 dependencies should be questioned for SRP violation"
Basically all answers on the question are agreeing that second approach is worst (together with me) because burring up the dependencies a class has prevents effective black box unit testing and makes harder refactoring. I already blogged about transparent vs. opaque DI, so I’ll skip beating the dead horse here.
The thing I do want here to discuss are the answers which are recommending in general replacing the first case with the single dependency on IServiceLocatorIContainer.
IServiceLocatorIContainer injection doesn’t make a lot of sense in general
There is no real advantage of using the IServiceLocator vs the DIContainer from the second solution. I mean we would be decoupled from the specific IoC container but the problems of low testability and hard refactoring would stay due to the same opaque nature of dependencies class has. In other words, from my point of view using singleton service locator in this sense is even better then the IServiceLocator being injected (same set of problems, one parameter less in constructor).
The only exception from this rule is the case when we have multiple components mapped to a service with a different key (IoC version of Strategy pattern implementation) there is no way to inject the one with a given key (as long they share the same interface) so injecting IContainer in that case is acceptable.
Setter type of dependency injection shouldn’t be used
Second type of answer is not to use constructor dependency injection but instead setter type of DI (I’ve blogged about the differences long time ago). Couple a years ago I was fan of the setter type from the same reasons (removes the constructor noise) but the set of problems I was facing in real world related to it convince me that it is much worse choice then the constructor type. The main reasons behind that opinion are primarily due to the facts that setter type of DI makes dependencies again opaque and (in this case) even more important result with creation of public API members which only purpose is to satisfy infrastructure needs which (I believe) is deeply wrong. No API members should be created just in order to satisfy the infrastructure andor unit testing needs.
Nikola’s 3rd law of IoC
Every dependency of the class has to be presented in a transparent manner in a class constructor.
Factories and IoC
The question contains a thought of injecting the factory interface which reminded me also on a discussion I had with one of my colleagues regarding usage of factories in certain scenarios (as proposed in Art Of Unit Testing – go buy that book in case you haven’t done that already).
IMO, using factories together with IoC doesn’t make a lot of sense because IoC container is in a sense “universal abstract factory”.
In other words, in my experience any time I thought about adding a factory I ended with much simpler IoC based solution so that’s why I would dare to say that “IoC kill the Factory star"
Q2: How do you approach dependencies that might be used, but may be expensive to create?
Very simple, don’t create them to be like that. A constructor of a class being resolved from a IoC should be as light as possible just defining (if any) its own dependencies. Any class initialization or implementation shouldn’t be implicitly triggered from constructor but instead explicitly by invoking a specific member on instance resolved from a container. That’s how resolving all of them could be done without any significant performance issues.
Nikola’s 4th law of IoC
Every constructor of a class being resolved should not have any implementation other then accepting a set of its own dependencies.
Q3: How to build object graph of MyClass?
Without going into the details of how to do this with given framework (which other did in the SO answers and I covered it for Unity here) I would like to emphasize again the need for moving the mapping definition and resolution from UI elements (as proposed as option question) to dedicated application bootstrapper classcomponent which (implementing the Builder design pattern) sole responsibility would be to define the mappings in a single place or orchestrating other component bootstrappers.
On the beginning of the application life cycle, bootstrapper would build up the dependencies removing (ideally) the need for other parts of code base to be aware of the IoC container awareness.
(More about Builder pattern in dusty but still good Jeremy’s blog post)
Nikola’s 5th law of IoC
IoC container should be explicitly used only in Bootstrapper. Any other “IoC enabled” code (including the unit tests) should be completely agnostic about the existence of IoC container."
Appendix
So here we go, my dear reader – my first blog post in a while. I decided to fight with my Twitter addiction which sucked up all of my blogging energy and to start writing down (in my awful English) the thoughts and experiences I collected in last year so stay tuned for the bunch of very diverse and (hopefully) amusing blog posts
Dependency injection in real world
Patrick left a comment on one of my previous blog posts asking a couple of very interesting questions that I’ve been asking myself too:
Is service locator legitimate way of doing IoC?
(I’ll use example code from that blog post as a base for my today blog post so in case you are idle enough you can go and check it out)
Dependency injection primer
Let me start with an example how “real” dependency injection implementation code from my blog post could look like:
using System;
using System.Collections.Generic;
namespace Example.UserManager
{
public class UserManagerIoC
{
private readonly IUserProvider userProvider;
public UserManagerIoC(IUserProvider userProvider)
{
this.userProvider = userProvider;
}
public int NumberOfUsersActiveInLast10Days(string userName)
{
var userCollection = this.userProvider.GetUserCollection();
int result = 0;
foreach (User user in userCollection)
{
if (user.Name.StartsWith(userName) && user.LastActivity > DateTime.Now.AddDays(-10))
result++;
}
return result;
}
}
}
As we can see from the simple code above, code has one constructor which accepts the IUserProvider parameter and then stores its pointer to a field so it can be used later in a method which performs some kind of business logic.
Key concept here to be noticed is that class have literally no clue where from and how userProvider would get injected.
How DI based unit test looks like?
I’ll use Microsoft Unity and Rhino mocks to write a test for the dependency injection primer.
Here it is:
using System.Collections.Generic;
using Example.UserManager;
using Microsoft.Practices.Unity;
using NUnit.Framework;
using Rhino.Mocks;
namespace UserManager.Test.IoC
{
[TestFixture]
public class UserManagerTestIoC
{
private MockRepository mockRepository;
private IUnityContainer unityContainer;
[SetUp]
public void Test_Init()
{
this.mockRepository = new MockRepository();
this.unityContainer = new UnityContainer();
}
[Test]
public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
{
var userProvider = this.mockRepository.DynamicMock<IUserProvider>();
// injecting to unity container mocked instance of user provider
this.unityContainer.RegisterInstance(userProvider);
using (this.mockRepository.Record())
{
Expect.Call(userProvider.GetUserCollection())
.Return(new List<User>());
}
using (this.mockRepository.Playback())
{
// using IoC container for UserManager construction
var userManager = this.unityContainer.Resolve<UserManagerIoC>();
// and then performing tested code
int numberOfUsers= userManager.NumberOfUsersActiveInLast10Days("X");
Assert.IsTrue(numberOfUsers == 0);
}
}
}
}
What I did in that test:
- I am instantiating UnityContainer in test set up to be used as IoC container.
- In first line of test method I am using Rhino mocks to create mock of IUserProvider and then I inject that mock to Unity IoC container
- In a first line of recording block, I set expectation that empty user collection would be returned
- In playback block, I get an instance of UserManagerIoC class by using IoC container Resolve factory method. (KEY POINT)
- IoC container would then:
- examine the constructor of UserManagerIoC class,
- see that IUserProvider parameter is requested
- try to find in IoC container registered service implementing IUserProvider interface
- mocked instance we injected at the beginning of the test would be found
- mocked instance would be injected to UserManagerIoC
- Method would be executed and the expected number of users checked
NOTE #1: You could get away from explicit dependency mocking by using AutoMockingContainer but I decide to do it anyhow in this post in order to increase example readability.
NOTE #2: You could also opt to use var userManager = new UserManager(userProvider) but this is not something typically you would do because userProvider can have it’s own dependencies and so on… Not using IoC container in the test would mean not using one of its most important features: auto dependency resolution.
Dependency injection upsides and downsides
As we can see, we were able to keep UserManager light and ignorant about IoC infrastructure, while utilizing the benefits dependency injection provides us (increased testability in this example)
Still there are couple of problems (not sure if I can call them like this) related to this implementation which I’ve witnessed in last couple of months and which can be summarized as:
- Brownfield scenarios
UserManager is already existing class built without having dependency injection on mind (no constructor exposing abstracted dependencies). While it is hard to sell the business value of refactoring UserManager internals to expose dependencies through constructor (sell tagline: to test it) it is mission impossible getting approval for updating all of the million places currently doing the UserManager um = new UserManager() to become unityContainer.Resolve<UserManager>() (Sith language : “What’s the business value?”) and without that change no DI going to happen.
- Code monkey scenarios
Vast majority of developers I know don’t get the IoC, TDD etc, which means that one would spend ton of time answering the“Why I can not just new the instance?”, “This is clearly an overkill…”, “Here it is him with his damn patterns making my life miserable”, “Why I need to decouple DB from my unit tests at all?”..
Although this reason might look “not-so-important”, if you are not lucky to work in TDD friendly environment, if you are working in company which DEV teams span across the globe this could be real show stopper.
- “TDD == unit test”
If you are doing unit tests AFTER the code is been done then it is very hard to sell to PMs the need for “all that complexity”.In other words, if they don’t get that in TDD the most important thing is not the “T” (test) but the “DD” (driven design) whole DI thing start to get harder to be sold
- “Why IoC framework X?”
”Why UnityContainer?” “Why not Castle?” “Why not Spring?” “Why not StructureMap?” “On my previous job I worked with XYZ and it is the best…”
ServiceLocator based dependency injection
Luckily, I think I found a way how to go around the restrictions mentioned above with keeping the dependency injection in place and high testability. I’ve wrote in more details in my DFT blog post series so here I’ll just summarize it…
The key points that solution has to achieve are:
- Core code implementation has to utilize dependency injection
- Code has to be “open for testing” but “close for development” (yes, I am aware how stupid this might sound and it it stupid thing – details bellow )
- DI enabling existing code is not allow to cause any breaking compatibility issues (KIC - “keep it cheap” design principle)
- No dependency on any particular IoC framework
Lets take a look at the same primer I’ve done with DI this time implemented using service locator
using System;
using Facade;
namespace Example.UserManager
{
public class UserManagerSL
{
private readonly IUserProvider userProvider;
public UserManagerSL(): this (ServiceLocator.Retrieve<IUserProvider>())
{
}
internal UserManagerSL(IUserProvider userProvider)
{
this.userProvider = userProvider;
}
public int NumberOfUsersActiveInLast10Days(string userName)
{
var userCollection = this.userProvider.GetUserCollection();
int result = 0;
foreach (User user in userCollection)
{
if (user.Name.StartsWith(userName) && user.LastActivity > DateTime.Now.AddDays(-10))
result++;
}
return result;
}
}
}
Main differences (compared to dependency injection primer) are:
- We still have public parameter less constructor
That parameter less constructor uses ServiceLocator to retreive instace of IUserProvider on a same way UnityContainer retrieved it in previous test.ServiceLocator is just a Facade wrapper around IoC container encapsulating the type of container and hiding not used features.
Achieved design goal: “Keep it cheap”
Achieved design goal: “No dependency on particular IoC framework” - In some bootstrapper class tied to app start event I will have to define ServiceLocator mapping for service implementing the IUserProvider so the code would work normally like it was working before the dependency injection
- Constructor taking IUserProvider parameter is now internal.
The assembly containing UserManagerSL class would contain next attribute[assembly: InternalsVisibleTo("UserManager.Test.SL")]
Result of this attribute would be that this constructor would be:
- visible to test assembly containing test methods using UserManagerSL
- not visible to any code outside of that test assembly (none of the “core DEV” would be aware of it)Achieved design goal: “Open for test, close for development”
Achieved design goal: “Dependency injection used in code”
How ServiceLocator based test looks like?
Here are two examples how the service locator code can be tested..
“White box” service locator test style
using System.Collections.Generic;
using Example.UserManager;
using Facade;
using NUnit.Framework;
using Rhino.Mocks;
namespace UserManager.Test.SL
{
[TestFixture]
public class UserManagerTestSL
{
private MockRepository mockRepository;
private IUserProvider userProvider;
[SetUp]
public void Test_Init()
{
this.mockRepository=new MockRepository();
// registering mock of IUserProvider with ServiceLocator
this.userProvider = this.mockRepository.DynamicMock<IUserProvider>();
ServiceLocator.InjectStub(this.userProvider);
}
[Test]
public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection_WithSL()
{
using (this.mockRepository.Record())
{
Expect.Call(this.userProvider.GetUserCollection())
.Return(new List<User>());
}
using (this.mockRepository.Playback())
{
// using internal constructor
var userManager = new UserManagerSL();
int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
Assert.IsTrue(numberOfUsers == 0);
}
}
}
}
In this testing style we feed the service locator with the list of internal dependencies we know it is been used by the tested code and then in our test method we totally don’t care about dependency injection (constructors used are empty, no service locator usage anywhere outside of SetUp method)
I personally don’t like this style of testing (based on intimate knowledge of tested code) but I’ve seeing it working in the past.
Using internal constructor
Second approach is based on the fact that internal constructor is accessible to test assembly which makes test built on this way very simple
using System.Collections.Generic;
using Example.UserManager;
using NUnit.Framework;
using Rhino.Mocks;
namespace UserManager.Test.SL
{
[TestFixture]
public class UserManagerTestSL
{
private MockRepository mockRepository;
[SetUp]
public void Test_Init()
{
this.mockRepository=new MockRepository();
}
[Test]
public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollection()
{
IUserProvider userProvider = mockRepository.DynamicMock<IUserProvider>();
using (mockRepository.Record())
{
Expect.Call(userProvider.GetUserCollection())
.Return(new List<User>());
}
using (mockRepository.Playback())
{
// using internal constructor
var userManager = new UserManagerSL(userProvider);
int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
Assert.IsTrue(numberOfUsers == 0);
}
}
}
}
In this example we don’t use at all service locator. Instead we simply inject mocked instance of user provider to internal constructor. All of the downsides of this approach (mentioned in dependency injection note #2) are applicable here to.
Using dependency injection
The best thing with my service locator based design approach is that while some of the “not so TDD skilled” developers can do testing on the first two ways, “TDD skilled” developer can still write exactly the same test as the one given in the dependency injection section of this blog post.
Check it for yourself:
[Test]
public void GetActiveUsers_TestCaseOfZeroUsers_WouldReturnEmptyCollectio_IoC()
{
var userProvider = this.mockRepository.DynamicMock<IUserProvider>();
// injecting to unity container mocked instance of user provider
ServiceLocator.InjectStub(userProvider);
using (this.mockRepository.Record())
{
Expect.Call(userProvider.GetUserCollection())
.Return(new List<User>());
}
using (this.mockRepository.Playback())
{
// using IoC container for UserManager construction
var userManager = ServiceLocator.Retrieve<UserManagerSL>();
// and then performing tested code
int numberOfUsers = userManager.NumberOfUsersActiveInLast10Days("X");
Assert.IsTrue(numberOfUsers == 0);
}
}
Summary
Most of the blog posts I’ve seen present an ideal “perfect day” situation setup for writing the test which is not always the case in real world.
In this kind of “not-so-perfect” situations, service locator based solution I’ve presented in that blog post allowed me to increase testability and introduce TDD into existing code bases and environments not so much interested in the TDD.
Source code for this blog post can be found here.
Fluent NHibernate – NHibernate without configuration files
NHibernate is great, (no doubt about it) but every time I was supposed to work with it, the fact that I had to manually type in all those xml configuration entries was something I really didn’t like at all.
The most important complains I personally have on NHibernate configuration files are:
- It is error prone
- Errors in configuration file can be hard to trace
- It is not refactoring friendly
- It is not C#, it is XML
I believe that the most important reason why NHibernate is not more widely adopted by general DEV population is exactly the “Java XML configuration” PIA feeling you have while working with it.
Great news for all of us from that group: NHibernate is possible to be used WITHOUT configuration files!
Who, what and where?
Jeremy Miller coded initial bits of the Fluent NHibernate project and then James Gregory with couple of guys more bring the project to Google code and they started finalizing it. OSS rules!
So, if you go to http://code.google.com/p/fluent-nhibernate/ you would see names of other project members together with the simple code illustrating the goal fluent nhibernate project tries to achieve.
As with the most OSS projects, to get the source code of FNH, download it from Subversion trunk located at http://fluent-nhibernate.googlecode.com/svn/trunk/
Solution file consist of couple of projects:
- LIb solution folder contains DLL you would be using in your application.
- Test project containing a bunch of unit tests which you can use as starting point to get detail understanding on how the things works.
- Quick start project which highlights most important concepts you need to start using NHibernate
Note: Project is initially built with NHibernate 2.0 which collides with Linq For NHibernate (using NHibernate 2.1) so I updated FNH project references to use 2.1 too
Fluent NHibernate in action
Solution project structure
In this blog post, I will use the same example Jimmy Nilsson used in his Applying Domain-Driven Design and Patterns: With Examples in C# and .NET NHibernate chapter so you can compare outcome of my blog post sample it with how it looked in his book (with the configuration files in place).
Solution file of today’s example contains 3 projects:
- BusinessLayer (“Domain”)
Contains definitions of entities which we use in modeling business use cases.
Important to be mentioned here is that BusinessLayer project doesn’t have any reference to neither other projects of this solution nor the “3pty dlls” such is NHibernate.dll - NHConfigMappings (“Mapping project”)
Contains ORM mapping definitions which enables nhibernate to persist to relational DB domain entities - NHCongigMappings.Test
Contains test fixture illustrating how mappings should be consumed and how nhibernate engine could be initialized without any xml configuration files
(Source code used in today blog post can be download from here)
Domain project
As you can see, it is very simple sample where we have entity customer class containing “embedded” Address value object and referencing the list of reference persons customer contacted.
Same diagram given in code would look like this
using System;
using System.Collections.Generic;
namespace CustomerConfiguration
{
public class Customer
{
public virtual Guid Id { get; set; }
public virtual string CustomerNumber { get; set; }
public virtual string Name { get; set; }
public virtual Address CustomerAddress { get; set; }
public virtual IList ReferencePersons { get; set; }
}
}
Address type will look like this:
namespace CustomerConfiguration
{
public class Address
{
public virtual string Street { get; set; }
public virtual string PostalCode { get; set; }
public virtual string Town { get; set; }
public virtual string Country { get; set; }
}
}
And ReferencePerson type would look like this:
using System;
namespace CustomerConfiguration
{
public class ReferencePerson
{
public virtual Guid Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string SurName { get; set; }
}
}
As you can see from the code above, NHibernate allows us fully persistent ignorant POCO software development: no special attributes, no special base class or interface…
Mapping project
Once we have domain logic defined, we need to provide information on how NHibernate should map our classes with appropriate DB entities: tables and columns.
For my example DB would look like this:
As you can see, although in my code I have separate Address class I don’t have it in DB. Instead I have it embedded in Customer table as last 4 columns. Also, table names in DB are in plural form while names of classes are in singular form.
Another small difference here is that in ReferencePerson class has a LastName property while DB has column SurName.
Mapping ReferencePerson
I won’t throw in here example of how that would look if I would use XML configuration file, because the whole point is to forget that ASAP
(In case you want to see it, check it out here)
In order to define NHibernate mapping, in FNH you need to create a mapping class for each one of entities (which is something Ayende don’t get).
That mapping class should inherit from ClassMap<T> class in order to get access to FHN members providing programmatic access over configuration settings
using CustomerConfiguration;
using FluentNHibernate.Mapping;
namespace NHConfigMappings
{
public class ReferencePersonMap : ClassMap<ReferencePerson>
{
public ReferencePersonMap()
{
TableName = “ReferencePersons”;
Id(x => x.Id).GeneratedBy.GuidComb()
.WithUnsavedValue(“00000000-0000-0000-0000-000000000000”);
Map(x => x.FirstName).WithLengthOf(50).CanNotBeNull();
Map(x => x.LastName,”SurName”).WithLengthOf(50).CanNotBeNull();
}
}
}
Main advantage of fluent interface is that it produces code with good readability, which I believe we can see from code snippet above.
In a class constructor, I am defining:
- What is the name of data table where the class will be persisted. In my example table name and class name differs so I had to define it here, but I think it is good practice to define it always, even they are implicitly the same by the default
- Which class property should be used as Identity Field populating table PK. In example I took I am using ReferenceMap.Id property where NHibernate generate its value using GuidComb value as performance effective type of GUID values. At the end I defined how unsaved value is looking like so NHibernate would be able to deduct how the class should be persisted (insert or update)
- That the FirstName property should be mapped to the column with the same name where the column length is 50 characters and null values are not allowed
- That the LastName property should be mapped to the column named “SurName” with the maximum length of 50 characters without null values being allowed
In my opinion main advantages here are that the configuration code is human readable and refactoring friendly (if I ever do changes on ReferencePerson class mapping file will be broken so we have “type safe” configuration settings)
Mapping Customer
Customer class mapping definition is stored in CustomerMap (implementing the ClassMap<Customer> class looking something like this
using CustomerConfiguration;
using FluentNHibernate.Mapping;
namespace NHConfigMappings
{
public class CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
TableName = “Customers”;
Id(x => x.Id).GeneratedBy.GuidComb()
.WithUnsavedValue”00000000-0000-0000-0000-000000000000”);
Map(x => x.Name).WithLengthOf(50);
Map(x => x.CustomerNumber).WithLengthOf(50);
HasMany<ReferencePerson>(x => x.ReferencePersons)
.Access.AsProperty()
.AsBag().WithKeyColumn("CustomerId")
.Cascade.All();
Component<Address>(x => x.CustomerAddress,
m =>
{
m.Map(x => x.Street).WithLengthOf(100);
m.Map(x => x.PostalCode).WithLengthOf(6);
m.Map(x => x.Town).WithLengthOf(30);
m.Map(x => x.Country).WithLengthOf(50);
});
}
}
}
In a class constructor, I am defining:
- The name of table to which this class map
- Customer.Id as primary key containing guid value
- Customer.Name is mapped to the Name nvarchar(50) column
- Customer.CustomerNumber is mapped to the CustomerNumber nvarchar(50) column
- Customer class contains collection of ReferencePerson instances stored in Customer.ReferencePersons property
which should be mapped in separate table (AsBag()) where role of FK will be performed by ReferencePerson.CustomerIdand with cascading of events (Insert of Customer will result with Insert of ReferencePerson etc)
- Customer contains property CustomerAddress of type Address as embed value where
- Address.Street is nvarchar(100) column
- Address.PostalCode is nvarchar(6) column
- Address.Town is nvarchar(30) column
- Address.Country is nvarchar(50) column
Once again, take a look at the class above. I have just described something which looks like typical use case we face in real world with something which (IMHO) has very high readability and it is easy to be written
Unit testing fluent nhibernate mappings
In order to present how those mappings should be used I wrote unit test project which will present:
- how this mappings are to be used
- how to configure nhibernate itself without the need for hibernate.cfg.xml file
For the purpose of this test I choose MS Test just for kicks (although I am mostly using MBUnit )
How to initialize nhibernate without hibernate.cfg.xml
Due to the fact that initializing nhibernate engine is slow, I am initializing it once per text fixture and in test fixture of this example nhibernate initialization routine in case of fluent nhibernate is a 5 step procedure:
- Initialize type implementing IPersistenceConfigurer (MSSqlConfiguration, SQLLiteConfiguration, PostgreSQLConfiguration are currently supported)
- use instance of that type (in my example instance of MSSqlConfiguration) to preset properties of NHibernate.Configuration instance
- create instance of FluentHibernate.PersistenceModel type
- use that instance to load the assembly containing mappings
- use that instance to inject mappings to nhibernate configuration instance
At the end of configuration sequence I have operational NHibernate configuration instance which I use to create session factory which I then store as a class field.
Once I have that SessionFactory field in place, each one of the test methods just uses it to create a session needed.
Let’s take a look at how this initialization routine could look in code
private static ISessionFactory _sessionFactory;
[ClassInitialize]
public static void FixtureInit(TestContext testContext)
{
// initialize persistance configurer
IPersistenceConfigurer persistenceConfigurer =
MsSqlConfiguration
.MsSql2005
.ConnectionString.Is(
“Data Source=.SQL2008;Initial Catalog=NHibernateBlog;"
+ "Integrated Security=True”)
.ShowSql();
// initialize nhibernate with persistance configurer properties
Configuration cfg = persistenceConfigurer
.ConfigureProperties(new Configuration());
// add mappings definition to nhibernate configuration
var persistenceModel = new PersistenceModel();
persistenceModel.addMappingsFromAssembly
(Assembly.Load(“NHConfigMappings”));
persistenceModel.Configure(cfg);
// set session factory field which is to be used in tests
_sessionFactory = cfg.BuildSessionFactory();
}
I think code above is simple enough (thanks to FNH) that it doesn’t need any extra explanations about its concrete implementation.
Nhibernate unit test method
Now when we have that session factory up and going, we would make only a simple test where we will create a new customer and try to store it in DB.
That test code could look like this:
[TestMethod]
public void ReferencePerson_Create_ShouldCreateRowInDb()
{
var customer = new Customer
{
Name = “John Doe”,
CustomerNumber = “12345”,
CustomerAddress = new Address
{
Street = “1st Mayson Street”,
PostalCode = “01754”,
Town = “Maynard”,
Country = “USA”
},
ReferencePersons = new List<ReferencePerson>
{
new ReferencePerson
{
FirstName = “Nikola”,
LastName = “Malovic”
}
}
};
ISession session = _sessionFactory.OpenSession();
Guid id=(Guid)session.Save(customer);
session.Flush();
session.Evict(customer);
var customerDB= session.Get<Customer>(id);
Assert.IsTrue( customerDB.Id == customer.Id && customerDB.Name == customer.Name
&& customerDB.CustomerAddress.Street == “1st Mayson Street”
&& customerDB.ReferencePersons[0].FirstName == “Nikola”);
}
At the beginning of the test method I create a new customer instance with CustomerAddress data and single ReferencePerson instance in ReferencePersons.
Then I use the sessionFactory created in test fixture set up, and create a session which then I use to persist customer instance. As a result of that persistence method call I am getting customer identity value used as PK value in DB.At the end of that persistence code I just flush the session in order to commit the changes.
Now when (hopefully) our customer is saved I need to test that and the usual way of testing save is to try to load the data from DB. That’s why I remove the customer instance from NHibernate Identity Map “cache” so I won’t get results from memory and then I am trying to retrieve data using the identity value I retrieved during persistence.
With the retrieved customer data I do just quick value check (in real world test this check would look different).
Test will pass therefore if retrieved data will match the data of customer instance created in this test.
Running the test
Once I run the test, I got successful test
And fast look at the DB shows that data are persisted
Test passed!
Conclusion
Purpose of this blog post was to present a way of using NHibernate different then the standard xml configuration approach most of people use right now working with NHibernate.
I hope you can see for yourself that it is VERY possible to use NHibernate without a single configuration file on very DEV friendly and intuitive way.
The example I presented here is just tip of the iceberg so I strongly encourage you to sync Fluent NHibernate source code and play with quick start and test projects.
Here are also some links you can check out too:
Happy Hibernating!

