views:

355

answers:

1

I have a project that I am experimenting with DI in. I am using Unity and things seem to work well for normal assemblies and the injections.

I am trying to further break dependencies with WCF services. The WCF service that I want to inject is created at runtime currently without using DI and I don't use the VS .net generated proxies:

MyService = new ChannelFactory<IMyService>("BasicHttpBinding_IMyService").CreateChannel();

Endpoint for the above is in the web.config:

<endpoint address="http://localhost:35806/MyService.svc"
       binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
       contract="Interfaces.IMyService" name="BasicHttpBinding_IMyService" />

I am trying to figure out how to map this WCF service to an interface via the web.config so that I can use constructor injection

In web.config the normal mapping occurs using the "mapTo" where you would specify the interface alias and an alias to a class you previously defined.

<type type="IMyService" mapTo="MyService">
 <lifetime type="singleton"/>
</type>

Since the WCF service proxy is created dynamically at run time I do not have this reference to "MyService" class instead it needs to pull from the "BasicHttpBinding_IMyService" endpoint for the service.

Any ideas on how this can be accomplished?

+1  A: 

The only way I see this working from the config file is to create a MyService class that implements IMyService - and behind the scenes it creates its own Channel (using the ChannelFactory code snippet) and essentially acts as a proxy.

But instead of that, why not just call

RegisterInstance<IMyService>(myServiceChannelInstance)

on your unity container and pass in an already created MyService channel instance?

Bryan Batchelder
+1 What you just described is an Abstract Factory - it is one of the standard solution to common DI challenges.
Mark Seemann
@Bryan: Thanks I did realize that I could use the instance to do this at runtime but I was trying to stick with the web.config for everything.What I think I am going to end up doing is having a custom portion in my web.config mapping the service endpoint to the interface and then loop through these at runtime. This way it doesn't have to be embedded within my app. I'll leave this open for now to see if anyone has alternatives to doing this with the native Unity config sections.
Jay