Can’t decide whether to host your WCF service in IIS or a Windows Service? Consider the additional steps you’ll need to perform, explain, troubleshoot, and write documentation for if you follow the IIS route:
- Ensure IIS is installed.
- Run aspnet_regiis -i to install .NET ISAPI module.
- Run ServiceModelReg –i to install handlers for *.svc file types.
- Creating, starting a new App Pool running as a domain account.
- Set your Application to use the new App Pool instead of DefaultAppPool.
Plus, EITHER: (II6/Server 2003)
- Ensure the .NET 2.0 Web Service Extension is enabled.
- Add the domain account to local IIS_WPG group.
- (If required) cscript.exe adsutil.vbs set W3SVC/AppPools/Enable32BitAppOnWin64 “true”
OR: (IIS7/Server 2008)
- Ensure IIS6 Compatibility components are installed so *.vdproj installers can run.
- Add the domain account to local IIS_IUSRS group.
- (If required) set Enable 32-Bit Applications = true
If you are working in an environment like ours with developers in London, servers in Germany, and the ops team in India, where getting server access is harder than getting an appointment with the pope, I’d recommend sticking with Windows Services unless you really need IIS.
December 7, 2010 | Leave your comment
I just got a strange validation bug, trying to buy something on eBay UK:

After about eight attempts (trying different browsers, local/international phone number prefixes etc), I emailed them to report it, and find out maybe if I am doing something wrong. Here is their response:
Hello Richard. My name is Elma from PayPal customer service.
I reviewed your account carefully to check why you are unable to use your card and saw that you were trying to pay a £555.00 GBP transaction with your credit card. It appears that this particular payment cannot be funded by a credit card because of our security model.
I would like to assure you that there is nothing wrong with your credit card or your PayPal account. As part of our commitment to protect you and all our customers, we review all transactions that go through us. This payment got declined because we detected that it might not be safe for you to use your credit card for this transaction. Don’t worry. I assure you that it’s just for this particular transaction. You can still use your credit card for your future transactions.
This is amazing. PayPal are reporting a permanent, this-form-will-never-work-so-don’t-bother-filling-it-out problem to users as an input validation error. And how do users react to validation errors? They double check their details and type them in again. And again. And again, until they’ve gone slightly mad, spending hours scrutinizing every pixel in every digit in their credit card and telephone number for mistakes.
In the end, it wasn’t until I contacted PayPal directly (hint: their feedback form is not exactly easy to find) that I was told my credit card would never work for this particular purchase, and the whole thing was a waste of time. (I wonder how many customers they lost who didn’t bother to fill out a bug report?)
If you are writing software like this, you have BIG problems.
November 30, 2010 | 1 comment

Have you ever seen this development cycle?
- Install new build
- App doesn’t start, doesn’t log any error why
- Go back to source code and add improved logging
- Install new build
- Read logs
- Fix the actual problem (usually some stupid configuration thing)
- Repeat steps 1-6 until all bugs are gone
Was it because of your code, or someone else’s? This sort of cycle is time consuming, frustrating, stressful, and makes you look helpless (or like a cowboy) in front of project managers and support staff.
If your app can’t produce logs your infrastructure staff can understand, then your app is not even close to production-readiness. If it doesn’t log clear errors, how can anyone hope to deploy and support it?
August 20, 2010 | Leave your comment
This week I’ve been working on a brownfield Castle-powered WCF service that was creating a separate NHibernate session on every call to a repository object.
Abusing NHibernate like this was playing all sorts of hell for our app (e.g. TransientObjectExceptions), and prevented us from using transactions that matched with a logical unit of work, so I set about refactoring it.
Goals
- One session per WCF operation
- One transaction per WCF operation
- Direct access to ISession in my services
- Rely on Castle facilities as much as possible
- No hand-rolled code to plug everything together
There are a plethora of blog posts out there to tackle this problem, but most of them require lots of hand-rolled code. Here are a couple of good ones — they both create a custom WCF context extension to hold the NHibernate session, and initialize/dispose it via WCF behaviours:
- NHibernate Session Per Request Using Castles WcfFacility
- NHibernate’s ISession, scoped for a single WCF-call
These work well, but actually, there is a much simpler way that only requires the NHibernate and WCF Integration facilities.
Option one: manual Session.BeginTransaction() / Commit()
The easiest way to do this is to register NHibernate’s ISession in the container, with a per WCF operation lifestyle:
windsor.AddFacility<WcfFacility>();
windsor.AddFacility("nhibernate", new NHibernateFacility(...));
windsor.Register(
Component.For<ISession>().LifeStyle.PerWcfOperation()
.UsingFactoryMethod(x => windsor.Resolve<ISessionManager>().OpenSession()),
Component.For<MyWcfService>().LifeStyle.PerWcfOperation()));
If you want a transaction, you have to manually open and commit it. (You don’t need to worry about anything else because NHibernate’s ITransaction rolls back automatically on dispose):
[ServiceBehavior]
public class MyWcfService : IMyWcfService
{
readonly ISession session;
public MyWcfService(ISession session)
{
this.session = session;
}
public void DoSomething()
{
using (var tx = session.BeginTransaction())
{
// do stuff
session.Save(...);
tx.Commit();
}
}
}
(Note of course we are using WindsorServiceHostFactory so Castle acts as a factory for our WCF services. And disclaimer: I am not advocating putting data access and persistence directly in your WCF services here; in reality ISession would more likely be injected into query objects and repositories each with a per WCF operation lifestyle (you can use this to check for lifestyle conflicts). It is just an example for this post.)
Anyway, that’s pretty good, and allows a great deal of control. But developers must remember to use a transaction, or remember to flush the session, or else changes won’t be saved to the database. How about some help from Castle here?
Option two: automatic [Transaction] wrapper
Castle’s Automatic Transaction Facility allows you to decorate methods as [Transaction] and it will automatically wrap a transaction around it. IoC registration becomes simpler:
windsor.AddFacility<WcfFacility>();
windsor.AddFacility("nhibernate", new NHibernateFacility(...));
windsor.AddFacility<TransactionFacility>();
windsor.Register(
Component.For<MyWcfService>().LifeStyle.PerWcfOperation()));
And using it:
[ServiceBehavior, Transactional]
public class MyWcfService : IMyWcfService
{
readonly ISessionManager sessionManager;
public MyWcfService(ISessionManager sessionManager)
{
this.sessionManager = sessionManager;
}
[Transaction]
public virtual void DoSomething()
{
// do stuff
sessionManager.OpenSession.Save(...);
}
}
What are we doing here?
- We decorate methods with [Transaction] (remember to make them virtual!) instead of manually opening/closing transactions. I put this attribute on the service method itself, but you could put it anywhere — for example on a CQRS command handler, or domain event handler etc. Of course this requires that the class with the [Transactional] attribute is instantiated via Windsor so it can proxy it.
- Nothing in the NHibernateFacility needs to be registered per WCF operation lifestyle. I believe this is because NHibernateFacility uses the CallContextSessionStore by default, which in a WCF service happens to be scoped to the duration of a WCF operation.
- Callers must not dispose the session — that will be done by castle after the transaction is commited. To discourage this I am using it as a method chain — sessionManager.OpenSession().Save() etc.
- Inject ISessionManager, not ISession. The reason for this is related to transactions: NHibernateFacility must construct the session after the transaction is opened, otherwise it won’t know to enlist it. (NHibernateFacility knows about ITransactionManger, but ITransactionManager doesn’t know about NHibernateFacility). If your service depends on ISession, Castle will construct the session when MyWcfService and its dependencies are resolved (time of object creation) before the transaction has started (time of method dispatch). Using ISessionManager allows you to lazily construct the session after the transaction is opened.
- In fact, for this reason, ISession is not registered in the container at all — it is only accessible via ISessionManager (which is automatically registered by the NHibernate Integration Facility).
This gives us an NHibernate session per WCF operation, with automatic transaction support, without the need for any additional code.
Update: there is one situation where this doesn’t work — if your WCF service returns a stream that invokes NHibernate, or otherwise causes NHibernate to load after the end of the method, this doesn’t work. A workaround for these methods is simply to omit the [Transaction] attribute (hopefully you’re following CQS and not writing the DB in your query!).
Update 2: See my follow up post with further discussion about this technique here.
August 17, 2010 | 5 comments
Lately I have become a big opponent of a popular anti-pattern: people insisting on splitting up their application tiers/layers into 5-10 separate Visual Studio projects and adding references between them. Double that number of projects if you want corresponding unit test project for each layer.
In fact, removing them has become one of the first steps I take when inheriting a legacy code base. If I were writing a book on refactoring Visual Studio solutions, I would call it Merge redundant assemblies. Here’s a diagram:

You don’t need to split your code across 50 gazillion projects. Next time you think of creating a new project in your solution, please remember the following:
- Visual Studio projects are for outputing assemblies. Namespaces are for organising code.
- Assemblies only need to be split if your deployment scenario demands it. Putting a client API library into a separate assembly makes sense because the same API assembly may be used between many apps, or in different App Domains. Deploying your domain model or data layer into a separate assembly does not make sense, unless other apps need them too.
- Each additional project slows down your build. A giant project with hundreds of classes will compile faster than a smaller number of classes split amongst multiple projects.
- Crossing assembly boundaries hurts runtime performance. Your app will start up slower, the ability to perform inlining and OS optimization is reduced, and additional security overhead is enforced between assemblies. Assemblies are supposed to be big and heavy; loading lots of little one goes against the CLR.
- You don’t need one test project for each assembly. One giant tests project is normally fine. The only case I have seen where it made sense to have separate test projects was for a client API which duplicated many of the server internal class names and we wanted to avoid overlap/namespace pollution.
- Common sense should be used to enforce one-way dependencies. Not assembly references.
Patrick Smacchia has a good list of valid/invalid use cases where separate assemblies are appropriate here.
August 16, 2010 | 4 comments


