In my Stateful service, I can write to the ServiceEventSource
by calling this:
ServiceEventSource.Current.ServiceMessage(this.Context, "this is my log message");
Does anyone know how I can make that same call in my Stateless WebAPI controller? It seems like I'm unable to get the context into the controller. I noticed it's only available in my OwinCommunicationListener
.
Basically, I want to be able to log my controllers like this:
public async Task<IHttpActionResult> Get(string id)
{
ServiceEventSource.Current.ServiceMessage(this.Context, "this is my log message");
//Do something
return Ok(100);
}
One way of solving this is to work with Dependency Injection and an IoC, much like you would with a regular WebAPI solution.
If you are using the out-of-the-box supplied
OwinCommuncationController
and theStartup
class you could initialize and add a container to theStartup.ConfigureApp(...)
method:You could use any IoC that you like, here I'll show it for TinyIoC but similar approach for any (Windsor, Unity, Ninject, AutoFac...).
For TinyIoC add the NuGet
TinyIoC
andTinyIoC.AspNetExtensions
and add a class that implementsIDependencyResolver
:Note, this is just the simples implementation, for a better look at this article http://blog.i-m-code.com/2014/04/15/tinyioc-mvc-and-webapi-configuration/
Not update your Startup to allow WebApi to use the DependencyResolver:
And finally register your dependency (
StatelessServiceContext
) in your service:Notice that you have to make a slight change to how you call the
Startup.ConfigureApp
method in order to supply your container as well.Now all you have to do is to add
StatelessServiceContext
as a dependency in the constructor of yourApiController
and store it as a member in your controller:And from within your controller actions use it:
There are many variations to how you can do this, when and where you can create the container, how to resolve the controllers and so on. There should be plenty of guides on how to setup ASP.NET WebApi and IoC dependency injection.