Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple example of IServiceBehavior and ApplyDispatchBehavior

I am trying to Plug Unity into a WCF Service Library with a Service Behavior.

I need a simple bare bones example of a Service Behavior.

All I want to do is setup my IOC Unity Container on startup of the WCF Service.

NOTE: I am not using a WCF Service Application. So I don't have access to ANY of the ASP.NET ways of doing this. From a concept point of view, a service behavior seems like the most elegant method. But I don't know how to set one up (what code do I need, were do I update the config files, etc).

like image 446
Vaccano Avatar asked Jun 30 '11 19:06

Vaccano


1 Answers

If you want to control the instancing of the WCF service instances, you'll need a service behavior to plug an IInstanceProvider for that. You can find a simple provider implementation (for an IoC container) in the post about that interface at http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/31/wcf-extensibility-iinstanceprovider.aspx.

Per the comments, if all you need is a simple IServiceBehavior, here's a sample implementation you can use.

public class StackOverflow_6539963
{
    public class MyServiceBehaviorAttribute : Attribute, IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            Console.WriteLine("In MyServiceBehaviorAttribute.ApplyDispatchBehavior");
            // do whatever initialization you need
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }
    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        string Echo(string text);
    }
    [MyServiceBehavior]
    public class Service : ITest
    {
        public string Echo(string text)
        {
            return text;
        }
    }
    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
        host.Open();
        Console.WriteLine("Host opened");

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}
like image 77
carlosfigueira Avatar answered Oct 05 '22 03:10

carlosfigueira