Thursday, January 19, 2012

StructureMap Initialize (or Configure) with ChannelFactory

Trying to configure StructureMap to use the ServiceModel ChannelFactory should be pretty easy right? Unless.. it just isn't working.

The channel factory creates proxies, which StructureMap has a problem with. For instance, if you tried to create an instance of the proxy, and build the mapping:
       StructureMap.ObjectFactory.Initialize  
         (  
           z =  
           {  
             //service  
             var basicHttpBinding = new BasicHttpBinding();  
             var endpointAddress = new EndpointAddress("http://localhost:62049/SendMessage.svc");  
             var channelFactory = new ChannelFactory(basicHttpBinding, endpointAddress);  
             var proxy = channelFactory.CreateChannel();  
             z.For().Use(proxy);  
           }  
         );  

You would receive a StructureMapConfigurationException:
StructureMap configuration failures:
Error:  104
Source:  Registry:  StructureMap.Configuration.DSL.Registry, StructureMap, Version=2.6.3.0, Culture=neutral, PublicKeyToken=e60ad81abae3c223
Type Instance 'edc26816-1ec5-4f0d-b401-b4504e8fb537' (Object:  Instawares.Correspondence.Contract.ServiceContract.ISendMessage) cannot be plugged into type Instawares.Correspondence.Contract.ServiceContract.ISendMessage, Instawares.Correspondence.Contract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
-----------------------------------------------------------------------------------------------
The resolution is much simpler, and provides more flexibility which is to allow StructureMap to handle creation of the object using the LambdaInstance Use(Func func):


 StructureMap.Configuration.DSL.Expressions.CreatePluginFamilyExpression
The function will handle the creation of the service proxy (and you can control the lifecycle of the object via the configuration as well).

Here's an example:

               StructureMap.ObjectFactory.Initialize
                (
                    z =
                    {
                        //service
                        var basicHttpBinding = new BasicHttpBinding();
                        var endpointAddress = new EndpointAddress("http://localhost:62049/SendMessage.svc");
                        var channelFactory = new ChannelFactory(basicHttpBinding, endpointAddress);
                        z.For().Use(channelFactory.CreateChannel);
                    }
                );

The object creation has been been transferred to the ChannelFactory, and StructureMap handles the creation of the proxy, and the life cycle of that proxy.

Resources
StructureMap
ChannelFactory(Of TChannel) Class

No comments: