This project is read-only.

Contextual Parameter Binding

Consider the following scenario: You have a WCF-Service that writes incoming messages to a database. The service is run inside IIS. Unity is used as DI container via a custom ServiceHostFactory.

This is a sample of how to do that by Rory Primrose. A very similar piece of code can be found in TecX.ServiceModel.Unity.

In the above scenario it is very easy to configure Unity to inject a ConnectionString into the service. Just specify an InjectionConstructor or use one of the features of TecX.Unity to do so.

But now what if you expose different endpoints of that service and depending on which endpoint the message arrives at you need to write to a different database? Thus you would have to inject a different ConnectionString.

In order to hook up Unity with the WCF infrastructure you need to implement the IInstanceProvider interface. This has the GetInstance(InstanceContext, Message) message. And the Message parameter contains the destination endpoint of the incoming call.

But how on earth can you hook up that URI with the Unity infrastructure all in your composition root?

This is how the implementation of GetInstance looks like.

public object GetInstance(InstanceContext instanceContext, Message message)
{
  return this.container.Resolve(this.serviceType);
}

If you change it like this:

public object GetInstance(InstanceContext instanceContext, Message message)
{
  using (new ContextScope(container, new ContextInfo("instanceContext", instanceContext), new ContextInfo("message", message)))
  {			
    return this.container.Resolve(this.serviceType);
  }
}

And add the following registration to you composition root:

container.RegisterType<IMyService, WritesToDatabaseService>(
  new InjectionConstructor("SomeConnectionString"),
  new DestinationToConnectionStringBinding("http://localhost/service", "AnotherConnectionString"));

Then Unity will use AnotherConnectionString if the message is sent to the endpoint listening at http://localhost/service and SomeConnectionString for every other destination.

The source code for this feature can be found in TecX.Unity (folder ContextualBinding) and the tests showing how to use that feature in TecX.Unity.ContextualBinding.Test. Have fun :)

Last edited Jun 11, 2012 at 9:25 AM by weberse, version 2

Comments

No comments yet.