pointer to service from ServiceHost - wcf

I have the following WCF code:
ServiceHost host = null;
if (host == null)
host = new ServiceHost(typeof(RadisService));
How can i get a pointer to my RadisService, to make calls with it?
Well it was really for testing purposes, but please allow me to ask the question anyway, for educational purposes. What happens if my service is running on a machine (using a GUI host), several clients from different remote machines connect to the service and through the GUI leave comments on my service.
The code on my service looks like this:
public class MyClass
{
[DataMember]
static Dictionary<String, Variable> m_Variables = new
Dictionary<String, Variable>();
....
}
[ServiceContract]
public interface IMyClassService
{
[OperationContract]
bool AddVariable(String name, Variable value);
[OperationContract]
bool RemoveVariable(String name);
[OperationContract]
bool GetVariable(string name, Variable variable);
[OperationContract] List<String> GetVariableDetails();
...
}
So from my service host GUI i would like to be able to access GetVariableDetails(), and preview all the comments added from all the different clients at this point. How would i achieve this?

If you make your service a singleton you can create an instance of the service and give it to the ServiceHost:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CalculatorService: ICalculatorService
{
....
CalculatorService service = new CalculatorService();
ServiceHost serviceHost = new ServiceHost(service, baseAddress);

You cannot. The ServiceHost will host 1-n service class instances to handle incoming requests, but those are typically "per-call", e.g. a service class instance is created when a new request comes in, a method is called on the service class, and then it's disposed again.
So the ServiceHost doesn't really have any "service" class instance at hand that it can use and call methods on.
What exactly are you trying to achieve?
Update: the service host should really not do anything besides hosting the service - it should definitely not be calling into the service itself.
What you're trying to achieve is some kind of an administrative console - a GUI showing the current comments in your system. Do this either via a direct database query, or then just have a GUI console to call into your service and get those entries - but don't put that burden on the ServiceHost - that's the wrong place to put this functionality.

Related

Server Side WCF Service : How to reference/interact with other server components

I have a fairly simple design question about interaction between a self hosted WCF Service and other business classes.
Here is the WCF service contract :
/// <summary>
/// Represent requests on hardware components made by a client to the controler service
/// </summary>
[ServiceContract(CallbackContract = typeof(IHardwareServiceCallback))]
public interface IHardwareService
{
[OperationContract(IsOneWay = true)]
void OpenLeftDrawer();
[OperationContract(IsOneWay = true)]
void OpenRightDrawer();
}
The service implementation
public class HardwareService : IHardwareService
{
public void OpenLeftDrawer()
{
}
public void OpenRightDrawer()
{
}
}
A class which purpose is to handle the business logic regarding client calls on the server
class DrawerRequestManager
{
// Server side Business logic to handle OpenDrawer requests from client
}
Hosting scenario
Uri adrbase = new Uri(srvConfig.Address);
var host = new ServiceHost(typeof(HardwareService), adrbase);
host.AddServiceEndpoint(typeof(IHardwareService), srvConfig.Binding, srvConfig.Address);
host.Open();
Since this is the host that is managing the service instance lifetime, what is the proper way to handle the link between the service instance and business logic classes (DrawerRequestManager for exemple).
I'm using IOC container but i'm also interested in the response when not using IOC container.
Thanks in advance !
WCF uses parameterless constructor to create service objects, but there is a way to alter that. You need to implement your own instance provider.
You can inject your instance provider via ServiceHostFactory: see here.
Alternatively you can inject instance provider by using custom attribute for your service: see here.
Either way gives you full control of how services instances are created. You can use IOC there or just call constructor manually passing any parameters you want (e.g. reference to DrawerRequestManager instance).

WCF Task based asynchronous callback

I have created WCF service in VS2015:
[ServiceContract(CallbackContract = typeof(IMyCallback))]
public interface IMyService { }
IMyCallback looks like:
[ServiceContract]
public interface IMyCallback {
[OperationContract]
Task<string> OnServerEvent(UserAppEventData evData);
I've built the server, run it, then added service reference (by right click on solution explorer).
The client object is defined as
[CallbackBehaviorAttribute(
ConcurrencyMode = ConcurrencyMode.Reentrant,
IncludeExceptionDetailInFaults = true,
UseSynchronizationContext = true,
ValidateMustUnderstand = true
)]
public class QMyClient : IMyCallback { }
Automatically generated interface implementation made method in sync manner:
public string OnServerEvent(UserAppEventData evData) { }
This code does't work (and isn't asynchronous) and hangs client at OnServerEvent.
When I changed code manuallly to
public async Task<string> OnServerEvent(UserAppEventData evData)
and have done the same in auto generated "service references\...\Reference.cs, all works fine. But I don't want to change Referenece.cs every time I'm updating Service Reference.
Is there any method to force "Update Service Reference" make TBA OperationContractAttribute on callback?
At ordinary WCF service direction everything works OK, VS generates task based operations.
By default the service reference you've added to solution doesn't have asynchronous operations, but you can enable them and decide which option you use for your async methods - task-based or old-fashion asynchronous. This option is available in Advanced settings for service reference.
If you're using a svcutil tool, it will create the task-based methods by default, however, you can change that behavior by some flags like /async or /syncOnly.
What #VMAtm suggested will work out just fine.
I think, you could also use ChannelFactory for this scenario. It is very flexible and you can then await on the service operations from client side. Additional benefit, you don't need to modify client when there are these kind of changes on service side.
Something like:
var channelFactory = new ChannelFactory<IService>(
"WSHttpBinding_IService" // endpoint name
);
IService channel = channelFactory.CreateChannel();
string result = await channel.OnServerEvent();
Console.WriteLine(result);
Please note that for this scenario, you will have to import common interface library to client side as dll because then it will need to know about contracts and data contracts.

Consuming wcf service with windows process?

I need initialize some structure in wcf service class as soon as possible after start of hosting service.
Now I host it in WinForms application and there I initialize this static structure.
ServiceHost host = new...
host.Open()...
new MyServiceClient().Initialize();
But I'm sure there is better way to do this. I know now it is inelegant solution...maybe little wcf-client running as windows process? (this client should be responsible only for calling this initializing method)
You can use the constructor of the service to do whatever initialization work is required.
// The service
public class MyService : IMyService {
// Constructor
public MyService() {
// Initialize things here
}
}
If the initialization work should only be performed once, you can make the constructor static. If the things being constructed are not static, you can make the service a singleton, depending on your performance needs. You can decorate the service with the following code to do that:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

How do I supply a specific instance of a class, to expose as my WCF service

I have a class that implements a plugin for an existing application.
I also have exposed that class as a WCF service. That part is working so far. The problem I am running into is that the application I am plugging into creates the instance of my class that I want to use.
Is there a way to pass an existing class instance to the WCF service host, to expose as a service endpoint?
I know (or can figure out) how to make a singleton instance of a WCF service, but that still won't help me. From what I can tell, the singleton instance will still be created and provided by WCF.
I have thought of other approaches, but I'd rather take this one if it is available to me.
Some code. This is in the constructor of my plugin:
// Setup the service host
var baseAddress = new Uri("http://localhost:8080/MyService/");
this.serviceHost = new ServiceHost(this.GetType(), baseAddress);
// Add our service endpoint
// Todo: Is there somewhere around here that I can provide an instance?
// Maybe in behavior somewhere?
this.serviceHost.AddServiceEndpoint(
typeof(ITheInterfaceMyClassDerivesFrom),
new BasicHttpBinding(),
""
);
// Add metadata exchange (so we see something when we go to that URL)
var serviceMetadataBehavior = this.serviceHost.Description.Behaviors
.Find<ServiceMetadataBehavior>();
if (serviceMetadataBehavior == null)
this.serviceHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
this.serviceHost.AddServiceEndpoint(
typeof(IMetadataExchange),
new CustomBinding(new HttpTransportBindingElement()),
"MEX"
);
This is in the plugin's OnStartedUp method (called by the application I am plugging into):
serviceHost.Open();
You need to use the other constructor for ServiceHost if you want to do this - check out the MSDN docs at http://msdn.microsoft.com/en-us/library/ms585487.aspx
public ServiceHost(
Object singletonInstance,
params Uri[] baseAddresses
)

WCF Service - runtime not seeing the ServiceContract on Interface

I'm new to WCF and trying to get my first service running. I'm close but stuck on this problem.
In my interface definition file, I have this:
[ServiceContract(Namespace="http://mysite.com/wcfservices/2009/02")]
public interface IInventoryService
{
[OperationContract]
string GetInventoryName(int InventoryID);
}
Then I have my class file (for the service) that inherits it:
public class InventoryService : IInventoryService
{
// This method is exposed to the wcf service
public string GetInventoryName(int InventoryID)
{
return "White Paper";
}
Finally, in my Host project I have this:
ServiceHost host = new ServiceHost(typeof(Inventory.InventoryService));
host.AddServiceEndpoint(typeof(Inventory.InventoryService), new NetTcpBinding(),
"net.tcp://localhost:9000/GetInventory");
host.Open();
Everything compiles fine, and when the host goes to add the service endpoint, it bombs with this: "The contract type Inventory.InventoryService is not attributed with ServiceContractAttribute. In order to define a valid contract, the specified type (either contract interface or service class) must be attributed with ServiceContractAttribute."
I know I'm missing something simple here. I have the interface clearly marked as a service contract and there's a reference to that project in the Host project.
ServiceHost host = new ServiceHost(typeof(Inventory.InventoryService));
host.AddServiceEndpoint(typeof(Inventory.InventoryService), new NetTcpBinding(),
"net.tcp://localhost:9000/GetInventory");
host.Open();
If your ServiceContract attribute is on the Interface not the concrete class, try the following:
ServiceHost host = new ServiceHost(typeof(Inventory.InventoryService));
host.AddServiceEndpoint(typeof(Inventory.IInventoryService), new NetTcpBinding(),
"net.tcp://localhost:9000/GetInventory");
host.Open();