Host DLL as WCF Service

Using .Net framework 4 we can host a DLL as WebServiceand here is how to do it. All you have to do is the following: Create an Interface for the DLL Code Add Reference to "using System.ServiceModel" in the code

Service Interface

// an interface as contract
namespace killercodes_in.Dll_as_WS
{
[ServiceContract()]
interface IWS_Class1
{
[OperationContract()]
int AddNum(int one, int two);

}
}





then you should implement the interface like


using System.ServiceModel;
using System.ServiceModel.Description;

// class implementing the contract(interface)
namespace killercodes_in.Dll_as_WS
{
// Service Implementation
public class WS_Class1:IWS_Class1
{
public int AddNum(int one, int two)
{
return one + two;
}
}
}

The reason using "System.ServiceModel.Description" reference is because we Need a host application to host this DLL as WS. So Add a new Class call it "Host_WS_Class1"
// Hosting WS
namespace killercodes_in.Dll_as_WS
{
public class Host_WS_Class1
{
public Uri httpUrl { get; set; }
public string Status { get; set; }
private ServiceHost WsSvcHost;
public bool IsLive { get; set; }

public Host_WS_Class1(string HostingURL)
{
//Create a URI to serve as the base address
httpUrl = new Uri(HostingURL);
//Create ServiceHost
WsSvcHost = new ServiceHost(typeof(killercodes_in.Dll_as_WS.WS_Class1), httpUrl);
//Add a service endpoint
WsSvcHost.AddServiceEndpoint(typeof(killercodes_in.Dll_as_WS.IWS_Class1), new WSHttpBinding(), "");
//Enable metadata exchange
ServiceMetadataBehavior svcMetaBehaviour = new ServiceMetadataBehavior();
svcMetaBehaviour.HttpGetEnabled = true;
WsSvcHost.Description.Behaviors.Add(svcMetaBehaviour);
IsLive = false;


}

public string Start()
{
//Start the Service
WsSvcHost.Open();
IsLive = true;
Status = string.Format("Service started at {0}", DateTime.Now.ToString().Replace('/', ':'));
return Status;
}

public string Stop()
{
//Start the Service
WsSvcHost.Close();
IsLive = false;
Status = string.Format("Service stopped at {0}", DateTime.Now.ToString().Replace('/', ':'));
return Status;
}
}
}





Now all you need is an application to call/host this DLL.
 
killercodes_in.Dll_as_WS.Host_WS_Class1 hostCls = new Host_WS_Class1("http://localhost:5000/NewSvc");
Console.WriteLine(hostCls.Start());
Console.ReadKey();