Skip to content

Access HTTP specific features in services

IcodeNet edited this page Aug 31, 2012 · 5 revisions

ServiceStack is based on http handlers, but ServiceStack provides a clean, dependency-free IService to implement your Web Services logic in. The philosophy behind this approach is that the less dependencies you have on your environment and its request context, the more testable and re-usable your services become.

Advantages for having dependency-free services

If you don't need to access the HTTP Request context there is nothing stopping you from having your same IService implementation processing requests from a message queue which we've done for internal projects (which incidentally is the motivation behind the asynconeway endpoint, to signal requests that are safe for deferred execution).

Injecting the IRequestContext into your Service

Although working in a clean-room can be ideal from re-usability and testability point of view, you stand the chance of missing out a lot of the features present in HTTP.

Just like using built-in Funq IOC container, the way to tell ServiceStack to inject the request context is by implementing the IRequiresRequestContext interface which will get the IRequestContext injected before each request.

	public interface IRequestContext : IDisposable
	{
		T Get<T>() where T : class;
		string IpAddress { get; }
		IDictionary<string, Cookie> Cookies { get; }
		EndpointAttributes EndpointAttributes { get; }
		IRequestAttributes RequestAttributes { get; }
		string MimeType { get; }
		string CompressionType { get; }
		string AbsoluteUri { get; }
		IFile[] Files { get; }
	}

Note: ServiceBase and RestServiceBase already implement IRequestContext. You can access the IRequestContext with base.RequestContext in these two classes.

This will allow your services to inspect any Cookies or download any Files that were sent with the request, without creating a hard dependency.

Note: To set Response Cookies or Headers, return the HttpResult object.