I followed : this article and implemented it in a WCF Service.
It allows us to create a instance of a Service that doesn't have a parameterless constructor, by implementing a custom IServiceBehavior, and then decorating the service with that Service Behavior, so instead of having for example:
[ServiceBehavior]
public class MyService : IMyService
I would have
[InstanceProviderBehavior]
public class MyService : IMyService
I then implement the ApplyDispatchBehavior like this:
foreach (ChannelDispatcher cd in serviceHostBase.ChannelDispatchers) {
foreach (EndpointDispatcher ed in cd.Endpoints) {
if (!ed.IsSystemEndpoint) {
Console.WriteLine("Using InstanceProviderBehaviorAttribute");
ed.DispatchRuntime.InstanceProvider = new ServiceInstanceProvider(Configuration.Instance.Container);
}
}
}
And to provide an instance of the service I just do:
public object GetInstance(InstanceContext instanceContext, Message message)
{
AlertQueryService result = Container.Resolve<AlertQueryService>();
return result;
}
I ran it in windows and it worked as expected. But in linux with mono, it throws the exception
Exception Default constructor not found for type MyService
which indicates that maybe mono is ignoring the InstanceProviderBehaviorAttribute.
Another thing i noticed was that the line:
Console.WriteLine("Using InstanceProviderBehaviorAttribute");
Is executed in windows when the service host is opened. While in linux when the service host is opened, it doesn't write that in the console. Also the exception in linux is not thrown when we open the service host, but when the IsInitiating operation is called in MyService:
[OperationContract(IsInitiating = true)]
void Initialize();
Which indicates that with mono the service instance is only being resolved when we call the IsInitiating operation.
Any idea why this is works in windows and not in linux with mono? And why is the initialization behavior different?
Thanks
Try adding an InstanceContextProvider as well as your InstanceProvider in your EndpointBehavior. It seems the Mono implementation of ChannelDispatcher.ListenerLoopManager.Setup doesn't like the idea of being sans InstanceContextProvider if there is no parameterless constructor.
The InstanceContextProvider can be essentially a no-op implementation. So long as there is an instance, it will pass that check in ListenerLoopManagerSetup and happily proceed to utilize your InstanceProvider.
Re: why the different implementation... Mono is a re-implementation rather than a cross-compilation or even port. Consider the Important Rules section of their Contribution Guidelines. It wasn't until very recently that developers could contribute to the project if they had so much as looked at MS source code.
Related
I have .net core console application, which is hosted as windows service.
I want to catch an event if the user logs off/shutdown the computer.
I have found ways to catch this event in .net framework (here & here).
But I cant figure out how to achieve this in .net core.
To create service I am using "ServiceBase" class. Sample code is as given below:
public class MyService : ServiceBase
{
readonly string LogPath = "D:\\TestAppService.txt";
#region Constructors
public MyService()
{
this.CanShutdown = true;
}
#endregion
#region Protected Functions
protected override void OnStart(string[] args)
{
//your code here
// call the base class so it has a chance
// to perform any work it needs to
base.OnStart(args);
}
protected override void OnStop()
{
//your code here
// Call the base class
base.OnStop();
}
protected override void OnShutdown()
{
using (StreamWriter sw = File.AppendText(LogPath))
{
sw.WriteLine("shutdown == true");
}
//your code here
base.OnShutdown();
}
#endregion
}
The OnStop and OnStart methods are being called.
but when I shutdown the computer my OnShutdown method is not called.
According to aspisof.net, you should be able to use the SessionEnding API. This is because it is listed as being exposed in the windows Compatibility Pack - available on NuGet here.
This article on learn.microsoft.com shows how you can include it in a .NET Core application.
tl;dr
Add the NuGet package
Target Windows only
One thing to note: this was originally designed to be a temporary fix for porting Windows specific .NET code over to .NET Core.
The more accepted way to implement Windows only features is to move as much code to .NET Standard libraries as possible, and to use conditional compilation directives to include platform specific code when building for that platform.
By design dotnet core is not "friendly" with platform specific stuff
(like listening to log off event seems to me).
The solution I use in one of Windows-hosted services is described here.
When application domain is forced to close by operating system on shutdown - there is a room for using AppDomain event handlers.
With .NET 4.5, my WCF creation using svcutil suddenly seems to break (I've been using only .NET 4.0 until very recently) ....
With the default settings I'm using to convert a pre-existing WSDL to my C# WCF proxy class:
c:> svcutil.exe /n:*,MyNamespace /out:WebService MyService.wsdl
I get this C# file created:
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="MyService.IMyService1")]
public interface IMyService1
{
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMyService1/IsAlive", ReplyAction="http://tempuri.org/IMyService1/IsAliveResponse")]
[System.ServiceModel.FaultContractAttribute(typeof(MyService.MyFault), Action="http://tempuri.org/IMyService1/IsAliveErrorInfoFault", Name="MyServiceErrorInfo", Namespace="http://schemas.datacontract.org/2004/07/MyService.Types")]
string IsAlive();
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMyService1/IsAlive", ReplyAction="http://tempuri.org/IMyService1/IsAliveResponse")]
System.Threading.Tasks.Task<string> IsAliveAsync();
This doesn't work - if I try to instantiate an implemention of this interface in a ServiceHost
using (ServiceHost svcHost = new ServiceHost(typeof(MyService01Impl)))
{
svcHost.Open();
Console.WriteLine("Host running ...");
Console.ReadLine();
svcHost.Close();
}
I get this error:
Cannot have two operations in the same contract with the same name, methods 'IsAlive' and 'IsAliveAsync' in type 'MyService01Impl' violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.
Why does svcutil suddenly generate code that doesn't work??
If I use the /async keyword with svcutil, then I get the "old-style" async pattern with BeginIsAlive and EndIsAlive and things work again - but how can I tell WCF / svcutil to generate no async stuff at all?
svcutil by default generates a proxy class with both synchronous and Task-based methods, eg:
public interface IService1
{
...
string GetData(int value);
...
System.Threading.Tasks.Task<string> GetDataAsync(int value);
...
}
To generate a proxy with only synchronous methods, you need to use /syncOnly. This will omit the Task-based version:
public interface IService1
{
...
string GetData(int value);
...
}
In both cases, the proxy class itself inherits from ClientBase:
public partial class Service1Client : System.ServiceModel.ClientBase<IService1>, IService1
Finally, the /serviceContract switch generates only the interface and DTOs necessary for generating a dummy service
I'm a newbie on the subject, so I'll try to make this as clear as I can...
I created a WcfModule, where I load the following package:
Bind<IDistributorService>().To<DistributorService>().InRequestScope().Intercept().With<ExceptionInterceptor>();
At first, I don't receive any error, but I put an InterceptAttribute on my function:
[AttributeUsage(AttributeTargets.Method)]
public sealed class HandleExceptionsAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Kernel.Get<ExceptionInterceptor>();
}
}
[HandleExceptions]
public virtual Result<List<DistributorDataContract>> GetDistributor(string id)
{
//...code...
I get an error in this function: (first line in method)
private ServiceHost CreateNewServiceHost(Type serviceType, Uri[] baseAddresses, WebHttpBehavior webBehavior, WebHttpBinding webHttpBinding)
{
var host = base.CreateServiceHost(serviceType, baseAddresses);
//...
}
With the error:
InvalidProxyConstructorArgumentsException was unhandled by user code
Can not instantiate proxy of class:
My.Namespace.DistributorService.
Could not find a parameterless constructor.
Anyone who knows what the problem could be? Thanks!
This exception is thrown by castle core dynamic proxy when it is instructed to create a "class proxy" which does not have a parameterless (default) constructor and no constructor-arguments are passed to castle (see source).
My best guess is, that when you use ninject interception by attributes, ninject will instruct castle core to create a class-proxy, no matter whether your binding is Bind<IFoo>().To<Foo>() or Bind<Foo>().ToSelf().
It seems a bit strange, however, that ninject is not resolving and passing along all required constructor parameters.
What is the implementation of DistributorService and what's the implementation of the base class of the class containing CreateNewServiceHost?
Workaround:
Of course, switching to the Intercept().With<TInterceptor>() syntax will probably also enable you to use interception (see http://codepyre.com/2010/03/using-ninject-extensions-interception-part-2-working-with-interceptors/)
I have a ServiceBehavior Attribute like this:
AdhocAuthenticationAndAuthorisation : IServiceBehavior
{
public AdhocAuthenticationAndAuthorisation(string systemName, string serviceName)
{
//Some code here.
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
//+ Other interface members.
}
This is used for some authentication and authorisation, the Attribute is used to bootstrap some context information that is used later, the context is set up in the Validate method, and works fine when i only use the Attribute on one service in the same apppool. However on a second service(different service interface) in the same apppool the Validate method of the second Attribute is never run if i instantiate the second service, at the same time. If I instantiate the first service and wait 5 seconds and instantiate the other, then the validate method is called.
This has been tested on different bindings and with aspNetCompatibilityEnabled = on or off. The services run on .net and iis 7.5
Does any one know how to solve this issue?
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.