I like to create and host WCF services. So far, I can create services that define contracts for services and data (interfaces), and define hosts and configuration parameters to achieve them (endpoint specifications).
Well, consider this piece of code defining a service and using it (no mention of the endpoints defined in app.config is shown here):
[ServiceContract] public interface IMyService { [OperationContract] string Operation1(int param1); [OperationContract] string Operation2(int param2); } public class MyService : IMyService { public string Operation1(int param1) { ... } public string Operation2(int param2) { ... } } public class Program { public static void Main(stirng[] args) { using (ServiceHost host = new ServiceHost(typeof(MyService))) { host.Open(); ... host.Close(); } } }
Well, this structure is good at creating something that can be called an autonomous service. What if I need my service to use objects of a larger application. For example, I need a service that does something based on a specific collection defined somewhere in my program (which hosts the service). The service must search in this collection and search and return a specific item.
The list I'm talking about is a program-managed list edited and edited by him.
I have the following questions:
1) How can I create a service capable of handling this list? I know that a possible option uses the overloaded ServiceHost constructor, which takes an Object instead of a Type service. So I could pass on my list. It's good?
[ServiceContract] public interface IMyService { [OperationContract] string Operation1(int param1); [OperationContract] string Operation2(int param2); } public class MyService : IMyService { private List<> myinternallist; public MyService(List<> mylist) {
This example should clarify. Is this a good way to do it? Am i right?
2) How to handle conflicts on this shared resource between my service and my application? When my application starts by hosting the service, my application can insert items into the list and delete them, the service can do the same. Do I need a mutex? how to handle this? Note that the concurrency issue is affecting two participants: the main application and the service. Itβs true that the service is single-user, but the application is listed !!! I assume that the service is called by an external object, when this happens, is the application still working correctly? Is there any concurrency in this case ???
Thankyou