james.kinneavy@sa.ucsb.edu (1) [Avatar] Offline
#1
I have been mulling approaches to dealing with WCF's vanilla constraint of only supporting the default constructor. I read the section of your book which exemplifies the use of creating your own service host factory and implementing IInstanceProvider which is, of course, one option I had already thought of. Another one, and I'm wondering what you might think of this, is to create an inherited class from the service (say MyConfiguredService : MyService), providing it with a default constructor, and calling the base class parameterized constructor with the results from a call to the container.

public class MyConfiguredService : MyService {
public MyConfiguredService(): base(ServiceLocator.Resolve<IMyService>()) {}
}

It seems to work, it's quick, and allows me to at least keep my services agnostic for testability. I realize from reading the anti-patterns your point about service locators and I've started to have this feeling myself as I see it propagated over a lot of code. In this case, it feels like it may be well encapsulated as a small piece of infrastructure code. Granted I haven't really tried it or thought out the implications too far. I thought I might just run it past you and see if you think this a) a reasonable approach under limited circumstances; or b) dear god no! and here's why.

Appreciate any feedback you might have.
mark.seemann (383) [Avatar] Offline
#2
Re: WCF Service Approach
As long as you have only a single service hosted in the same project, that derived class simply becomes your Composition Root. In that case it should be fine.

The advantage of that approach is that it's simple and easy to understand.

The disadvantage is that it doesn't address the scenario where you have more than one service in the same host and you'd like to share certain dependency instances among multiple services. That may not be a very common scenario, so your proposed approach may be applicable in the majority of cases. I'm just pointing out what are the limitations so that you can make an informed decision.

On a slightly different note I'd say that creating a container-based IInstanceProvider is an effort you'd have to do only once. After that, it's a pure infrastructure component you can use again and again. Although it sounds complicated, it has really low maintenance costs, so I'd personally still go for that solution... but I've also been called a purist by lots of people smilie