Search Results

Search found 125 results on 5 pages for 'servicehost'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Route WCF ServiceHost to another computer

    - by I2nfo
    GoodDay, I'm not a guru when it comes to WCF, but i do know the basics. My question is, how do i create a ServiceHost on machine X, while the code is on machine Y? if i build and run this code on my dev machine(localhost) : servicehost = new ServiceHost(typeof(MyService1)); servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(),"net.tcp://my.datacenter.com/MyApp/MyService1"); //This is normally set to localhost. What implementation must be done on the datacenter server, so that if i had to point to http://my.datacenter.com/MyApp/MyService1 , it will route the service operation to my dev machine (localhost). However, the datacenter should not be accessible via the internet. It is a possible infrastructure that we researching to see if we can create a service bus type architecture so that all our customers can invoke other customer services running on their respective machines just by calling our datacenter url. We have looked at Windows Azure, but we have our own datacenter infrasture that we wish to leverage off. Come think of it, we kind of building our own Azure, on a very very basic scale. How does one go creating this? Thanks in Advance

    Read the article

  • WCF - Automatically create ServiceHost for multiple services

    - by Rajesh Pillai
    WCF - Automatically create ServiceHost for multiple services Welcome back readers!  This blog post is about a small tip that may make working with WCF servicehost a bit easier, if you have lots of services and you need to quickly host them for testing. Recently I was encountered a situation where we were faced to create multiple service host quickly for testing.  Here is the code snippet which is pretty self explanatory.  You can put this code in your service host which in this case is  a console application. class Program   {       static void Main(string[] args)       { // Stores all hosts           List<ServiceHost> hosts = new List<ServiceHost>();           try           { // Get the services element from the serviceModel element in the config file               var section = ConfigurationManager.GetSection("system.serviceModel/services") as ServicesSection;               if (section != null)               {                   foreach (ServiceElement element in section.Services)                   { // NOTE : If the assembly is in another namespace, provide a fully qualified name here in the form // <typename, namespace> // For e.g. Business.Services.CustomerService, Business.Services                       var serviceType = Type.GetType(element.Name); // Get the typeName                        var host = new ServiceHost(serviceType);                       hosts.Add(host); // Add to the host collection                       host.Open(); // Open the host                   }               }               Console.ReadLine();           }           catch (Exception e)           {               Console.WriteLine(e.Message);               Console.ReadLine();           }           finally           {               foreach (ServiceHost host in hosts)               {                   if (host.State == CommunicationState.Opened)                   {                       host.Close();                   }                   else                   {                       host.Abort();                   }               }           }       }   } I hope you find this useful.  You can make this as a windows service if required.

    Read the article

  • Creating a WCF ServiceHost object takes three to four minutes on some PCs

    - by Steve
    Hello, I have created a WCF service which does not use the app.config to configure itself. However, it takes three to four minutes on some PCs to construct the ServiceHost object. Thinking there was something wrong with my service, I constructed a simple Hello, World service and tried it with that. I have the same issue. According to the profiler, all this time is spent reading in configuration for the service. So I have two questions really. Is it possible to disable reading config from the XML? More importantly, does anyone have any idea why this might be taking such an inordinate amount of time? Here is the sample service: [ServiceContract] public interface IMyService { [OperationContract] string GetString(); } [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService : IMyService { public string GetString() { return "Hello, world!"; } } class Program { static void Main(string[] args) { Uri epAddress = new Uri("http://localhost:8731/Test"); Uri[] uris = new Uri[] { epAddress }; MyService srv = new MyService(); ServiceHost host = new ServiceHost(srv, uris); // this line takes 3-4 minutes host.AddServiceEndpoint(typeof(IMyService), new WSHttpBinding(), "Test"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); host.Open(); return; } } I need for design reasons to create the service and pass it in as an object, rather than passing it in as a type. If there's any more information that can be of use, please let me know. Many thanks.

    Read the article

  • Castle WCF DefaultServiceHostFactory in IIS: Accessing the ServiceHost

    - by user250837
    I am attempting to move from a self hosting architecture to hosting under IIS 6, primarily to take advantage of built in dynamic compression. I am using the Castle DefaultServiceHostFactory to provide the service to IIS in the .svc file. However, I need to programmatically specify certain end points and behaviours and I do not know how to retrieve the current ServiceHost. Is this be possible, or should I just look at other methods of compression independent of IIS?

    Read the article

  • WCF Service worker thread communicate with ServiceHost thread

    - by Brent
    I have a windows NT Service that opens a ServiceHost object. The service host context is per-session so for each client a new worker thread is created. What I am trying to do is have each worker thread make calls to the thread that started the service host. The NT Service needs to open a VPN connection and poll information from a device on the remote network. The information is stored in a SQL database for the worker threads to read. I only want to poll the device if there is a client connected, which will reduce network trafic. I would like the worker threads to tell the service host thread that they are requesting information and start the polling and updating the database. Everything is working if the device is alway being polled and the database being updated.

    Read the article

  • Self hosted WCF ServiceHost/WebServiceHost Concurrency/Peformance Design Options (.NET 3.5)

    - by Kyle
    So I'll be providing a few functions via a self hosted (in a WindowsService) WebServiceHost (not sure how to process HTTP GET/POST with ServiceHost), one of which may be called a large amount of the time. This function will also rely on a connection in the appdomain (hosted by the WindowsService so it can stay alive over multiple requests). I have the following concerns and would be oh so thankful for any input/thoughts/comments: Concurrent access - how does the WebServiceHost handle a bunch of concurrent requests. Are they queued and processes sequentially or are new instances of the contracts automagically created? WebServiceHost - WindowsService communication - I need some form of communication from the WebServiceHost to the hosting WindowsService for things like requesting a new session if one does not exist. Perhaps implementing a class which extends the WebServiceHost with events which the WindowsService subscribes to... (unless there is another way I can set off an event in the WindowsService when a request is made...) Multiple WebServiceHosts or Contracts - Would it give any real performance gain to be running multiple WebServiceHost instances in different threads (one per endpoint perhaps?) - A better understanding of the first point would probably help here. WSDL - I'm not sure why (probably just need to do more reading), but I'm not sure how to get the WebServiceHost base endpoint to respond with a WDSL document describing the available contract. Not required as all the operations will be done via GET requests which will not likely change, but it would be nice to have... That's about it for the moment ;) I've been reading a lot on WCF and wish I'd gotten into it long ago, but definitely still learning.

    Read the article

  • Run WCF ServiceHost with multiple contracts

    - by Sam
    Running a ServiceHost with a single contract is working fine like this: servicehost = new ServiceHost(typeof(MyService1)); servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService1"); servicehost.Open(); Now I'd like to add a second (3rd, 4th, ...) contract. My first guess would be to just add more endpoints like this: servicehost = new ServiceHost(typeof(MyService1)); servicehost.AddServiceEndpoint(typeof(IMyService1), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService1"); servicehost.AddServiceEndpoint(typeof(IMyService2), new NetTcpBinding(), "net.tcp://127.0.0.1:800/MyApp/MyService2"); servicehost.Open(); But of course this does not work, since in the creation of ServiceHost I can either pass MyService1 as parameter or MyService2 - so I can add a lot of endpoints to my service, but all have to use the same contract, since I only can provide one implementation? I got the feeling I'm missing the point, here. Sure there must be some way to provide an implementation for every endpoint-contract I add, or not?

    Read the article

  • WCF Web/ServiceHost - Singletons and initialisation

    - by Kyle
    I have some Service class which is defined as InstanceContextMode.Single, and is well known in the hosting application. (The host creates an instance, and passes that to the WebServiceHost) Hosting app:WebServiceHost host = null; SomeService serviceInstance = new SomeService("text", "more text"); host = new WebServiceHost(serviceInstance, baseUri); Problem: When I go to use the variables initialised when the service is created (ie, when a call is made to the service), they are either null or empty... Am I wrong in assuming that as the instance being initialised in the hosting application is used for each request to the WebServiceHost? Any pointers here would be great.

    Read the article

  • Fix: WCF - The type provided as the Service attribute value in the ServiceHost directive could not

    - by Ken Cox [MVP]
    I wanted to expose some raw data to users in my current ASP.NET 3.5 web site project. I created a subdirectory called ‘datafeeds’ and added a WCF Data Service. I wired the dataservice up to the Entity Framework class and, on running the ItemDataService.svc file, was greeted with: The type  <> provided as the Service attribute value in the ServiceHost directive could not be found So why couldn’t it find the class? It was right there in the… oops! Instead of putting the ItemDataService.vb...(read more)

    Read the article

  • How to host your own http-like server using ServiceHost or its analog capable to host WCF services?

    - by Ole Jak
    I use ServiceHost for hosting WCF cervices. I want to host near to my WCF services my own tcp programm (like WCF service but with out WCF) for direct sockets operations (like lien to some sort of broadcasting TCP stream) I want to use ServiceHost for somehow simplyfiing proces of creating my TCP sender\listener, to somehow control namespaces (so I would be able to let my clients to send TCP streams directly into my service using some nice URLs like www.example.com:34123/myserver/stream?id=1 or www.example.com:34123/myserver/stream?id=222 and so that I will not be bothered with Idea of 1 client for 1 socket at one time moment, BTW I realy want to keep my WCF services on the same port as my own server or what it is...) Can any body please help me with this?

    Read the article

  • How to host your own http-like server using ServiceHost?

    - by Ole Jak
    I use ServiceHost for hosting WCF cervices. I want to host near to my WCF services my own tcp programm (like WCF service but with out WCF) for direct sockets operations (like lien to some sort of broadcasting TCP stream) I want to use ServiceHost for somehow simplyfiing proces of creating my TCP sender\listener, to somehow control namespaces (so I would be able to let my clients to send TCP streams directly into my service using some nice URLs like www.example.com:34123/myserver/stream?id=1 or www.example.com:34123/myserver/stream?id=222 and so that I will not be bothered with Idea of 1 client for 1 socket at one time moment, BTW I realy want to keep my WCF services on the same port as my own server or what it is...) Can any body please hrlp me with this?

    Read the article

  • Fix: WCF - The type provided as the Service attribute value in the ServiceHost directive could not

    I wanted to expose some raw data to users in my current ASP.NET 3.5 web site project. I created a subdirectory called datafeeds and added a WCF Data Service. I wired the dataservice up to the Entity Framework class and, on running the ItemDataService...(read more)...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How does WAS/IIS manage ServiceHost instances?

    - by foosnazzy
    It appears that WAS will call ServiceHostFactory.CreateHost() once per each service implementation. How does WAS manage the lifetime of the ServiceHost/ServiceHostFactory? We have a custom factory/host that is occasionally being re-initialized. I'm wondering if WAS is recycling itself or it has some other reason to re-create the ServiceHostFactory/ServiceHost. I'm guessing the ServiceHostFactory gets fired up for the AppDomain and is a singleton, can someone confirm?

    Read the article

  • Is this a correct way to host a WCF service?

    - by mafutrct
    For some testing code, I'd like to be able to host a WCF service in only a few lines. I figured I'd write a simple hosting class: public class WcfHost : IDisposable where Implementation : class where Contract : class { public readonly string Address = "net.tcp://localhost:8000/"; private ServiceHost _Host; public WcfHost () { _Host = new ServiceHost (typeof (Implementation)); var binding = new NetTcpBinding (); var address = new Uri (Address); _Host.AddServiceEndpoint ( typeof (Contract), binding, address); _Host.Open (); } public void Dispose () { ((IDisposable) _Host).Dispose (); } } That can be used like this: using (var host = new WcfHost<ImplementationClass, ContractClass> ()) { Is there anything wrong with this approach? Is there a flaw in the code (esp. about the disposing)?

    Read the article

  • WCF threading - non-responsive UI

    - by Sphynx
    Hi everyone. I'm trying to configure some WCF stuff. Currently, I have a server which allows remote users to download files, and client. In the server, I use a ServiceHost class. I assume it should be running on a separate thread, however, the server UI (WinForms) becomes locked when someone downloads a file. Is there a way to manage the WCF threading model? Thank you!

    Read the article

  • How to host WCF service and TCP server on same socket?

    - by Ole Jak
    Tooday I use ServiceHost for self hosting WCF cervices. I want to host near to my WCF services my own TCP programm for direct sockets operations (like lien to some sort of broadcasting TCP stream) I need control over namespaces (so I would be able to let my clients to send TCP streams directly into my service using some nice URLs like example.com:port/myserver/stream?id=1 or example.com:port/myserver/stream?id=anything and so that I will not be bothered with Idea of 1 client for 1 socket at one time moment, I realy want to keep my WCF services on the same port as my own server or what it is so to be able to call www.example.com:port/myWCF/stream?id=222...) Can any body please help me with this? I am using just WCF now. And I do not enjoy how it works. That is one of many resons why I want to start migration to clear TCP=) I can not use net-tcp binding or any sort of other cool WS-* binding (tooday I use the simpliest one so that my clients like Flash, AJAX, etc connect to me with ease). I needed Fast and easy in implemrnting connection protocol like one I created fore use with Sockets for real time hi ammount of data transfering. So.. Any Ideas? Please - I need help.

    Read the article

  • Consume WCF Service InProcess using Agatha and WCF

    - by REA_ANDREW
    I have been looking into this lately for a specific reason.  Some integration tests I want to write I want to control the types of instances which are used inside the service layer but I want that control from the test class instance.  One of the problems with just referencing the service is that a lot of the time this will by default be done inside a different process.  I am using StructureMap as my DI of choice and one of the tools which I am using inline with RhinoMocks is StructureMap.AutoMocking.  With StructureMap the main entry point is the ObjectFactory.  This will be process specific so if I decide that the I want a certain instance of a type to be used inside the ServiceLayer I cannot configure the ObjectFactory from my test class as that will only apply to the process which it belongs to. This is were I started thinking about two things: Running a WCF in process Being able to share mocked instances across processes A colleague in work pointed me to a project which is for the latter but I thought that it would be a better solution if I could run the WCF Service in process.  One of the projects which I use when I think about WCF Services is AGATHA, and the one which I have to used to try and get my head around doing this. Another asset I have is a book called Programming WCF Services by Juval Lowy and if you have not heard of it or read it I would definately recommend it.  One of the many topics that is inside this book is the type of configuration you need to communicate with a service in the same process, and it turns out to be quite simple from a config point of view. <system.serviceModel> <services> <service name="Agatha.ServiceLayer.WCF.WcfRequestProcessor"> <endpoint address ="net.pipe://localhost/MyPipe" binding="netNamedPipeBinding" contract="Agatha.Common.WCF.IWcfRequestProcessor"/> </service> </services> <client> <endpoint name="MyEndpoint" address="net.pipe://localhost/MyPipe" binding="netNamedPipeBinding" contract="Agatha.Common.WCF.IWcfRequestProcessor"/> </client> </system.serviceModel>   You can see here that I am referencing the Agatha object and contract here, but also that my binding and the address is something called Named Pipes.  THis is sort of the “Magic” which makes it happen in the same process. Next I need to open the service prior to calling the methods on a proxy which I also need.  My initial attempt at the proxy did not use any Agatha specific coding and one of the pains I found was that you obviously need to give your proxy the known types which the serializer can be aware of.  So we need to add to the known types of the proxy programmatically.  I came across the following blog post which showed me how easy it was http://bloggingabout.net/blogs/vagif/archive/2009/05/18/how-to-programmatically-define-known-types-in-wcf.aspx. First Pass So with this in mind, and inside a console app this was my first pass at consuming a service in process.  First here is the proxy which I made making use of the Agatha IWcfRequestProcessor contract. public class InProcProxy : ClientBase<Agatha.Common.WCF.IWcfRequestProcessor>, Agatha.Common.WCF.IWcfRequestProcessor { public InProcProxy() { } public InProcProxy(string configurationName) : base(configurationName) { } public Agatha.Common.Response[] Process(params Agatha.Common.Request[] requests) { return Channel.Process(requests); } public void ProcessOneWayRequests(params Agatha.Common.OneWayRequest[] requests) { Channel.ProcessOneWayRequests(requests); } } So with the proxy in place I could then use this after opening the service so here is the code which I use inside the console app make the request. static void Main(string[] args) { ComponentRegistration.Register(); ServiceHost serviceHost = new ServiceHost(typeof(Agatha.ServiceLayer.WCF.WcfRequestProcessor)); serviceHost.Open(); Console.WriteLine("Service is running...."); using (var proxy = new InProcProxy()) { foreach (var operation in proxy.Endpoint.Contract.Operations) { foreach (var t in KnownTypeProvider.GetKnownTypes(null)) { operation.KnownTypes.Add(t); } } var request = new GetProductsRequest(); var responses = proxy.Process(new[] { request }); var response = (GetProductsResponse)responses[0]; Console.WriteLine("{0} Products have been retrieved", response.Products.Count); } serviceHost.Close(); Console.WriteLine("Finished"); Console.ReadLine(); } So what I used here is the KnownTypeProvider of Agatha to easily get all the types I need for the service/proxy and add them to the proxy.  My Request handler for this was just a test one which always returned 2 products. public class GetProductsHandler : RequestHandler<GetProductsRequest,GetProductsResponse> { public override Agatha.Common.Response Handle(GetProductsRequest request) { return new GetProductsResponse { Products = new List<ProductDto> { new ProductDto{}, new ProductDto{} } }; } } Second Pass Now after I did this I started reading up some more on some resources including more by Davy Brion and others on Agatha.  Now it turns out that the work I did above to create a derived class of the ClientBase implementing Agatha.Common.WCF.IWcfRequestProcessor was not necessary due to a nice class which is present inside the Agatha code base, RequestProcessorProxy which takes care of this for you! :-) So disregarding that class I made for the proxy and changing my code to use it I am now left with the following: static void Main(string[] args) { ComponentRegistration.Register(); ServiceHost serviceHost = new ServiceHost(typeof(Agatha.ServiceLayer.WCF.WcfRequestProcessor)); serviceHost.Open(); Console.WriteLine("Service is running...."); using (var proxy = new RequestProcessorProxy()) { var request = new GetProductsRequest(); var responses = proxy.Process(new[] { request }); var response = (GetProductsResponse)responses[0]; Console.WriteLine("{0} Products have been retrieved", response.Products.Count); } serviceHost.Close(); Console.WriteLine("Finished"); Console.ReadLine(); }   Cheers for now, Andy References Agatha WCF InProcess Without WCF StructureMap.AutoMocking Cross Process Mocking Agatha Programming WCF Services by Juval Lowy

    Read the article

  • WCF using windows service

    - by Lijo
    Hi, I am creating a WCF service which is to be hosted in Windows Service. I created a console application as follows I went to management console (services.msc) and started the service. But I got the following error "The LijosWindowsService service on Local Computer started and then stopped. Some services stop automatically if they have no work to do, for example, the Performance Logs and Alerts service" I went to the event viewer and got the following "Service cannot be started. System.InvalidOperationException: Service 'Lijo.Samples.WeatherService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element." Could you please let me know what is the missing link here? File name [LijosService.cs] using System.ComponentModel; using System.ServiceModel; using System.ServiceProcess; using System.Configuration; using System.Configuration.Install; namespace Lijo.Samples { [ServiceContract(Namespace = "http://Lijo.Samples")] public interface IWeather { [OperationContract] double Add(double n1, double n2); } public class WeatherService : IWeather { public double Add(double n1, double n2) { double result = n1 + n2; return result; } } public class MyWindowsService : ServiceBase { public ServiceHost serviceHost = null; public MyWindowsService() { // Windows Service name ServiceName = "LijosWindowsService"; } public static void Main() { ServiceBase.Run(new MyWindowsService()); } protected override void OnStart(string[] args) { if (serviceHost != null) { serviceHost.Close(); } serviceHost = new ServiceHost(typeof(WeatherService)); serviceHost.Open(); } protected override void OnStop() { if (serviceHost != null) { serviceHost.Close(); serviceHost = null; } } } // ProjectInstaller [RunInstaller(true)] public class ProjectInstaller : Installer { private ServiceProcessInstaller myProcess; private ServiceInstaller myService; public ProjectInstaller() { myProcess = new ServiceProcessInstaller(); myProcess.Account = ServiceAccount.LocalSystem; myService = new ServiceInstaller(); myService.ServiceName = "LijosWindowsService"; Installers.Add(myProcess); Installers.Add(myService); } } } App.config <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="Lijo.Samples.WeatherService" behaviorConfiguration="WeatherServiceBehavior"> <host> <baseAddresses> <add baseAddress="http://localhost:8000/ServiceModelSamples/LijosService"/> </baseAddresses> </host> <endpoint address="" binding="wsHttpBinding" contract="Lijo.Samples.IWeather" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WeatherServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> Thanks Lijo

    Read the article

  • Xaml parse exception is thrown when i define a duplex contract

    - by Yaroslav
    Hi! I've got a WPF application containing a WCF service. The Xaml code is pretty simple: Enter your text here Send Address: Here is the service: namespace WpfApplication1 { [ServiceContract(CallbackContract=typeof(IMyCallbackContract))] public interface IMyService { [OperationContract(IsOneWay = true)] void NewMessageToServer(string msg); [OperationContract(IsOneWay = true)] bool ServerIsResponsible(); } [ServiceContract] public interface IMyCallbackContract { [OperationContract] void NewMessageToClient(string msg); [OperationContract] void ClientIsResponsible(); } /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); //behavior.HttpGetEnabled = true; //behavior. ServiceHost serviceHost = new ServiceHost( typeof(MyService), new Uri("net.tcp://localhost:8080/")); serviceHost.Description.Behaviors.Add(behavior); serviceHost.AddServiceEndpoint( typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex"); serviceHost.AddServiceEndpoint( typeof(IMyService), new NetTcpBinding(), "ServiceEndpoint"); serviceHost.Open(); MessageBox.Show( "server is up"); // label1.Content = label1.Content + String.Format(" net.tcp://localhost:8080/"); } } public class MyService : IMyService { public void NewMessageToServer(string msg) { } public bool ServerIsResponsible() { return true; } } } I am getting a Xaml parse exception in Line 1, what can be the problem? Thanks!

    Read the article

  • How to call a wpf singleton service within a wpf singleton service without hanging?

    - by Michael Hedgpeth
    I have two services, one that calls another. Both are marked as singletons as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class Service : IService And I set these up with a ServiceHost as follows: ServiceHost serviceHost = new ServiceHost(singletonElement); serviceHost.Open(); When the parent service tries to call the child service on the same machine, the parent service hangs, waiting for the child service. I'm already considering moving away from the singleton model, but is there anything wrong with my approach? Is there an explanation for this behavior and a way out of it?

    Read the article

  • How to call a WCF singleton service within a WCF singleton service without hanging?

    - by Michael Hedgpeth
    I have two services, one that calls another. Both are marked as singletons as follows: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class Service : IService And I set these up with a ServiceHost as follows: ServiceHost serviceHost = new ServiceHost(singletonElement); serviceHost.Open(); When the parent service tries to call the child service on the same machine, the parent service hangs, waiting for the child service. I'm already considering moving away from the singleton model, but is there anything wrong with my approach? Is there an explanation for this behavior and a way out of it?

    Read the article

  • Adding IoC Support to my WCF service hosted in a windows service (Autofac)

    - by user137348
    I'd like to setup my WCF services to use an IoC Container. There's an article in the Autofac wiki about WCF integration, but it's showing just an integration with a service hosted in IIS. But my services are hosted in a windows service. Here I got an advice to hook up the opening event http://groups.google.com/group/autofac/browse_thread/thread/23eb7ff07d8bfa03 I've followed the advice and this is what I got so far: private void RunService<T>() { var builder = new ContainerBuilder(); builder.Register(c => new DataAccessAdapter("1")).As<IDataAccessAdapter>(); ServiceHost serviceHost = new ServiceHost(typeof(T)); serviceHost.Opening += (sender, args) => serviceHost.Description.Behaviors.Add( new AutofacDependencyInjectionServiceBehavior(builder.Build(), typeof(T), ??? )); serviceHost.Open(); } The AutofacDependencyInjectionServiceBehavior has a ctor which takes 3 parameters. The third one is of type IComponentRegistration and I have no idea where can I get it from. Any ideas ? Thanks in advance.

    Read the article

  • TDD and WCF behavior

    - by Frederic Hautecoeur
    Some weeks ago I wanted to develop a WCF behavior using TDD. I have lost some time trying to use mocks. After a while i decided to just use a host and a client. I don’t like this approach but so far I haven’t found a good and fast solution to use Unit Test for testing a WCF behavior. To Implement my solution I had to : Create a Dummy Service Definition; Create the Dummy Service Implementation; Create a host; Create a client in my test; Create and Add the behavior; Dummy Service Definition This is just a simple service, composed of an Interface and a simple implementation. The structure is aimed to be easily customizable for my future needs.   Using Clauses : 1: using System.Runtime.Serialization; 2: using System.ServiceModel; 3: using System.ServiceModel.Channels; The DataContract: 1: [DataContract()] 2: public class MyMessage 3: { 4: [DataMember()] 5: public string MessageString; 6: } The request MessageContract: 1: [MessageContract()] 2: public class RequestMessage 3: { 4: [MessageHeader(Name = "MyHeader", Namespace = "http://dummyservice/header", Relay = true)] 5: public string myHeader; 6:  7: [MessageBodyMember()] 8: public MyMessage myRequest; 9: } The response MessageContract: 1: [MessageContract()] 2: public class ResponseMessage 3: { 4: [MessageHeader(Name = "MyHeader", Namespace = "http://dummyservice/header", Relay = true)] 5: public string myHeader; 6:  7: [MessageBodyMember()] 8: public MyMessage myResponse; 9: } The ServiceContract: 1: [ServiceContract(Name="DummyService", Namespace="http://dummyservice",SessionMode=SessionMode.Allowed )] 2: interface IDummyService 3: { 4: [OperationContract(Action="Perform", IsOneWay=false, ProtectionLevel=System.Net.Security.ProtectionLevel.None )] 5: ResponseMessage DoThis(RequestMessage request); 6: } Dummy Service Implementation 1: public class DummyService:IDummyService 2: { 3: #region IDummyService Members 4: public ResponseMessage DoThis(RequestMessage request) 5: { 6: ResponseMessage response = new ResponseMessage(); 7: response.myHeader = "Response"; 8: response.myResponse = new MyMessage(); 9: response.myResponse.MessageString = 10: string.Format("Header:<{0}> and Request was <{1}>", 11: request.myHeader, request.myRequest.MessageString); 12: return response; 13: } 14: #endregion 15: } Host Creation The most simple host implementation using a Named Pipe binding. The GetBinding method will create a binding for the host and can be used to create the same binding for the client. 1: public static class TestHost 2: { 3: 4: internal static string hostUri = "net.pipe://localhost/dummy"; 5:  6: // Create Host method. 7: internal static ServiceHost CreateHost() 8: { 9: ServiceHost host = new ServiceHost(typeof(DummyService)); 10:  11: // Creating Endpoint 12: Uri namedPipeAddress = new Uri(hostUri); 13: host.AddServiceEndpoint(typeof(IDummyService), GetBinding(), namedPipeAddress); 14:  15: return host; 16: } 17:  18: // Binding Creation method. 19: internal static Binding GetBinding() 20: { 21: NamedPipeTransportBindingElement namedPipeTransport = new NamedPipeTransportBindingElement(); 22: TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement(); 23:  24: return new CustomBinding(textEncoding, namedPipeTransport); 25: } 26:  27: // Close Method. 28: internal static void Close(ServiceHost host) 29: { 30: if (null != host) 31: { 32: host.Close(); 33: host = null; 34: } 35: } 36: } Checking the service A simple test tool check the plumbing. 1: [TestMethod] 2: public void TestService() 3: { 4: using (ServiceHost host = TestHost.CreateHost()) 5: { 6: host.Open(); 7:  8: using (ChannelFactory<IDummyService> channel = 9: new ChannelFactory<IDummyService>(TestHost.GetBinding() 10: , new EndpointAddress(TestHost.hostUri))) 11: { 12: IDummyService svc = channel.CreateChannel(); 13: try 14: { 15: RequestMessage request = new RequestMessage(); 16: request.myHeader = Guid.NewGuid().ToString(); 17: request.myRequest = new MyMessage(); 18: request.myRequest.MessageString = "I want some beer."; 19:  20: ResponseMessage response = svc.DoThis(request); 21: } 22: catch (Exception ex) 23: { 24: Assert.Fail(ex.Message); 25: } 26: } 27: host.Close(); 28: } 29: } Running the service should show that the client and the host are running fine. So far so good. Adding the Behavior Add a reference to the Behavior project and add the using entry in the test class. We just need to add the behavior to the service host : 1: [TestMethod] 2: public void TestService() 3: { 4: using (ServiceHost host = TestHost.CreateHost()) 5: { 6: host.Description.Behaviors.Add(new MyBehavior()); 7: host.Open();¨ 8: …  If you set a breakpoint in your behavior and run the test in debug mode, you will hit the breakpoint. In this case I used a ServiceBehavior. To add an Endpoint behavior you have to add it to the endpoints. 1: host.Description.Endpoints[0].Behaviors.Add(new MyEndpointBehavior()) To add a contract or an operation behavior a custom attribute should work on the service contract definition. I haven’t tried that yet.   All the code provided in this blog and in the following files are for sample use. Improvements I don’t like to instantiate a client and a service to test my behaviors. But so far I have' not found an easy way to do it. Today I am passing a type of endpoint to the host creator and it creates the right binding type. This allows me to easily switch between bindings at will. I have used the same approach to test Mex Endpoints, another post should come later for this. Enjoy !

    Read the article

  • How to configure maximum number of transport channels in WCF using basicHttpBinding?

    - by Hemant
    Consider following code which is essentially a WCF host: [ServiceContract (Namespace = "http://www.mightycalc.com")] interface ICalculator { [OperationContract] int Add (int aNum1, int aNum2); } [ServiceBehavior (InstanceContextMode = InstanceContextMode.PerCall)] class Calculator: ICalculator { public int Add (int aNum1, int aNum2) { Thread.Sleep (2000); //Simulate a lengthy operation return aNum1 + aNum2; } } class Program { static void Main (string[] args) { try { using (var serviceHost = new ServiceHost (typeof (Calculator))) { var httpBinding = new BasicHttpBinding (BasicHttpSecurityMode.None); serviceHost.AddServiceEndpoint (typeof (ICalculator), httpBinding, "http://172.16.9.191:2221/calc"); serviceHost.Open (); Console.WriteLine ("Service is running. ENJOY!!!"); Console.WriteLine ("Type 'stop' and hit enter to stop the service."); Console.ReadLine (); if (serviceHost.State == CommunicationState.Opened) serviceHost.Close (); } } catch (Exception e) { Console.WriteLine (e); Console.ReadLine (); } } } Also the WCF client program is: class Program { static int COUNT = 0; static Timer timer = null; static void Main (string[] args) { var threads = new Thread[10]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread (Calculate); threads[i].Start (null); } timer = new Timer (o => Console.WriteLine ("Count: {0}", COUNT), null, 1000, 1000); Console.ReadLine (); timer.Dispose (); } static void Calculate (object state) { var c = new CalculatorClient ("BasicHttpBinding_ICalculator"); c.Open (); while (true) { try { var sum = c.Add (2, 3); Interlocked.Increment (ref COUNT); } catch (Exception ex) { Console.WriteLine ("Error on thread {0}: {1}", Thread.CurrentThread.Name, ex.GetType ()); break; } } c.Close (); } } Basically, I am creating 10 proxy clients and then repeatedly calling Add service method. Now if I run both applications and observe opened TCP connections using netstat, I find that: If both client and server are running on same machine, number of tcp connections are equal to number of proxy objects. It means all requests are being served in parallel. Which is good. If I run server on a separate machine, I observed that maximum 2 TCP connections are opened regardless of the number of proxy objects I create. Only 2 requests run in parallel. It hurts the processing speed badly. If I switch to net.tcp binding, everything works fine (a separate TCP connection for each proxy object even if they are running on different machines). I am very confused and unable to make the basicHttpBinding use more TCP connections. I know it is a long question, but please help!

    Read the article

  • Duplex Contract GetCallbackChannel always returns a null-instance

    - by Yaroslav
    Hi! Here is the server code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.Runtime.Serialization; using System.ServiceModel.Description; namespace Console_Chat { [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IMyCallbackContract))] public interface IMyService { [OperationContract(IsOneWay = true)] void NewMessageToServer(string msg); [OperationContract(IsOneWay = false)] bool ServerIsResponsible(); } [ServiceContract] public interface IMyCallbackContract { [OperationContract(IsOneWay = true)] void NewMessageToClient(string msg); [OperationContract(IsOneWay = true)] void ClientIsResponsible(); } [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class MyService : IMyService { public IMyCallbackContract callback = null; /* { get { return OperationContext.Current.GetCallbackChannel<IMyCallbackContract>(); } } */ public MyService() { callback = OperationContext.Current.GetCallbackChannel<IMyCallbackContract>(); } public void NewMessageToServer(string msg) { Console.WriteLine(msg); } public void NewMessageToClient( string msg) { callback.NewMessageToClient(msg); } public bool ServerIsResponsible() { return true; } } class Server { static void Main(string[] args) { String msg = "none"; ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); ServiceHost serviceHost = new ServiceHost( typeof(MyService), new Uri("http://localhost:8080/")); serviceHost.Description.Behaviors.Add(behavior); serviceHost.AddServiceEndpoint( typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex"); serviceHost.AddServiceEndpoint( typeof(IMyService), new WSDualHttpBinding(), "ServiceEndpoint" ); serviceHost.Open(); Console.WriteLine("Server is up and running"); MyService server = new MyService(); server.NewMessageToClient("Hey client!"); /* do { msg = Console.ReadLine(); // callback.NewMessageToClient(msg); } while (msg != "ex"); */ Console.ReadLine(); } } } Here is the client's: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.Runtime.Serialization; using System.ServiceModel.Description; using Console_Chat_Client.MyHTTPServiceReference; namespace Console_Chat_Client { [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IMyCallbackContract))] public interface IMyService { [OperationContract(IsOneWay = true)] void NewMessageToServer(string msg); [OperationContract(IsOneWay = false)] bool ServerIsResponsible(); } [ServiceContract] public interface IMyCallbackContract { [OperationContract(IsOneWay = true)] void NewMessageToClient(string msg); [OperationContract(IsOneWay = true)] void ClientIsResponsible(); } public class MyCallback : Console_Chat_Client.MyHTTPServiceReference.IMyServiceCallback { static InstanceContext ctx = new InstanceContext(new MyCallback()); static MyServiceClient client = new MyServiceClient(ctx); public void NewMessageToClient(string msg) { Console.WriteLine(msg); } public void ClientIsResponsible() { } class Client { static void Main(string[] args) { String msg = "none"; client.NewMessageToServer(String.Format("Hello server!")); do { msg = Console.ReadLine(); if (msg != "ex") client.NewMessageToServer(msg); else client.NewMessageToServer(String.Format("Client terminated")); } while (msg != "ex"); } } } } callback = OperationContext.Current.GetCallbackChannel(); This line constanly throws a NullReferenceException, what's the problem? Thanks!

    Read the article

1 2 3 4 5  | Next Page >