Unity Dependency Injection for WCF services

萝らか妹 提交于 2019-12-03 18:01:45

问题


Can someone direct me to a good example of Unity Dependency Injection for WCF services? Any blog or msdn article will also help.


回答1:


This answer gives an example on how to enable DI in WCF with Castle Windsor.

Just replace the IWindsorContainer with an IUnityContainer in the example and you should be all set, although you may also want to change the class names from WindsorXyz to UnityXyz :)




回答2:


To inject dependencies into WCF services I had to implement a service host factory.

I have found a step-by-step tutorial here.

Basically you have to:

  1. Implement an IInstanceProvider to create services using the container
  2. Implement an IServiceBehavior to set the instance provider in the endpoint dispatcher
  3. Extend ServiceHost to add the new service behavior
  4. Extend ServiceHostFactory to create the new service host



回答3:


I'm about to give a try to Unity.Wcf library (https://github.com/ViceIce/unity.wcf), at first sight looks pretty good. I've read in this article this:

If you are hosting your WCF service within a Windows Service using a ServiceHost, replace the ServiceHost instance with the custom Unity.Wcf.UnityServiceHost. You will find that the UnityServiceHost takes in a Unity container as its first parameter but is otherwise identical to the default ServiceHost.

As it is my case I'm going to do this...

   class Program
{
    static void Main(string[] args)
    {
        // 1st Initialize the Host (Configures Container and Factories)
        ServiceHostController.Initialize();

        // 2nd Create a URI to serve as the base address.
        var baseAddress = new Uri("http://localhost:54321/BlaBlaBla/");

        // 3rd Create a UnityServiceHost instance
        var myService = new UnityServiceHost(ServiceHostController.UnityContainer, typeof(MyService), baseAddress);

        try
        {  //etcetera...

And it worked for me, I still have to refactor some things and add features and methods but the starting point works like a charm.

I hope it helps.



来源:https://stackoverflow.com/questions/3764212/unity-dependency-injection-for-wcf-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!