Unity Dependency Injection of a WCF service via web.config
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.
开发者_StackOverflow中文版<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?
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?
I wrote a set of Unity extensions last year that achieve exactly this. You can download my toolkit from http://neovolve.codeplex.com/releases/view/19004 which has this support.
Have a look at the chm file for the toolkit. The documentation for the Neovolve.Toolkit.Unity.ProxyParameterValueElement will describe how to achieve what you want with this toolkit.
精彩评论