Tuesday, 23 April 2013

Extending ServiceStack

I’ve been using ServiceStack on a couple of projects recently and I have to say I’m well impressed, it’s a superbly written set of assemblies, really well thought out, extremely fast and extensible too.

One of the things I’ve been struggling with however is how to inject an implementation of an interface into the pipeline before everything else. The API I’m exposing requires a couple of Http headers to be present, and not only do these need to be verified as present, but I want to use them to initialise one of the services (we’ll call it IMerchantTokenService) that other parts of the application need.

The general process I’d like to go through is as follows…

  • When an HTTP Request comes in, check for the headers
    • If they exist, create an implementation of IMerchantTokenService that contains these headers and stuff it into the IOC container. If not, throw an exception.
    • As IMerchantTokenService is now registered in the IOC container, when I resolve any other services that have this as a requirement it will be injected into all of these other services too.

Like most things, until you “get” the API you’re left wondering how to implement a feature, and once you know the API it’s second nature. This was one of those days.

After some fruitless tinkering I took a step back and thought – my headers requirement sounds a lot like an HTTP session (even though it’s used for something different). So I went and had a look at how ServiceStack deals with sessions and, sure enough, that was also the place where I could plug in my stuff. It’s easy when you know how.

The feature I was searching for is called a “Plugin”. Simply put, a plugin allows you to attach some extra processing to the request pipeline in ServiceStack, and you can get in before your service is instantiated and therefore affect which service(s) are available to import into your dependencies.

Writing a plugin

Creating a plugin is trivially easy – create a class that derives from IPlugin, override the Register method and bingo, you’re in business…

Code Snippet
/// <summary>
/// This class provides a plug-in that's called prior to any services being
/// executed. It verifies that the required header values are in place,
/// and registers a service so that other objects can access these
/// values later in the cycle
/// </summary>
public class MerchantTokenFeature : IPlugin
    /// <summary>
    /// Add a callback so that we get called when a request comes in
    /// </summary>
    /// <param name="appHost">The hosting provider</param>
    public void Register(IAppHost appHost)
        if (null == appHost)
            throw new ArgumentNullException("appHost");

        _appHost = appHost;

    /// <summary>
    /// Process the request headers
    /// </summary>
    /// <param name="request">The Http request</param>
    /// <param name="response">The Http response</param>
    private void PreFilter(IHttpRequest request, IHttpResponse response)
        string apiKey = request.Headers[Headers.APIKey];
        string merchantIdentifier = request.Headers[Headers.MerchantIdentifier];

        if ((null == apiKey) || (null == merchantIdentifier))
            throw HttpError.Unauthorized(string.Format("You must send the {0} and {1} headers", Headers.APIKey, Headers.MerchantIdentifier));

        _appHost.Register<IMerchantTokenService>(new MerchantTokenService(apiKey, merchantIdentifier));

    private IAppHost _appHost;

This plug-in hooks an additional entry into the PreRequestFilters collection, and so when a request comes in my PreFilter method is called and I can check the Http headers and then manually construct the additional service.

Registering your PlugIn

The only other requirement is to register the plug-in. In the Configure method of your AppHostBase derived class just add the plugin…

Code Snippet
public override void Configure(Funq.Container container)
    SetConfig(new EndpointHostConfig { ServiceStackHandlerFactoryPath = "api" });
    Plugins.Add(new MerchantTokenFeature());

That’s it – up and working. I can now import IMerchantTokenService wherever I need, and know that this dependency will be available by the time my service gets instantiated and it starts looking for it’s own dependencies.


Richard Majece said...

I have a huge amount of applications in my phone so I was scared when I lost it. https://cellspyapps.org/track-phone-number/ helped me to track my phone number and find it)

Veronica Segura said...

I love to read your blog post. You are really doing good to attract the readers. Actually I don’t make comments on every post I visit. Just wish to say your article is as surprising. Must say it is such a nice post. I used to be checking continuously this blog and I’m inspired! Extremely helpful info particularly the final phase :) I care for such information a lot. I was seeking this certain info for a very long time. Thanks and best of luck for your future work. Feel free to visit my site: Write my Essay for any writing related help.

jacklinemelda said...

Our company is the best online solution in offering college term papers for sale since we hire professional writers who have years of experience in buy custom essay papers services.

meldaresearch said...

We are the best writing company providing Buy College Papers Online to students across the globe.We are a UK based company and have been operational since 2005 where we have assisted thousands of students in attaining high marks in Custom College Essay Writing Service.

Sam said...

As consumerism continues to grow exponentially, it has become increasingly essential for marketers to understand consumer behavior so as to guide them in effective product development, which in turn, addresses the needs and wants of the consumers. Consumer behavior can best be defined as “the study of the processes involved when individuals or groups select, purchase, use or dispose of products, services, ideas or experiences to satisfy needs and desires”. Get assignment help on smartphone purchase by our expert writers based in Australia.

noor said...

نقل عفش من جدة الى دبي نقل عفش من جدة الى دبي

Priya Escorts said...

Mumbai Escorts is the most beautiful Call Girl escort service source in Mumbai at very low-cost rates or photos available on whatsapp. High Profile Russian Escorts and Sexy Call Girls in Mumbai in call and out Call 24*7

Bhilwara Escorts | Call Girls in Bhilwara | Bhilwara Call Girls | Escorts in Bhilwara | Russian Bhilwara Escorts | Call Girls Service in Bhilwara | Escort Service in Bhilwara
Punjabi Call Girls in Bhilwara | Bhilwara Escort | Independent Bhilwara Escorts | Independent Escorts in Bhilwara | Bhilwara Escorts Agency

john said...

محمد لطفی
هوروش بند
مهدی احمدوند
حمید هیراد

riya said...

Help full post, lots of information
Uipath Tutorial
Types of uipath
Uipath Architecture
Products fo Uipath
Workflow in Uipath
process of uipath
uipath installation
creating script in uipath
project types and templates in uipath

John said...

محمد لطفی
هوروش بند
مهدی احمدوند
حمید هیراد دانلود آهنگ های پرطرفدار جدید

riya said...

Help full post, lots of information
zoho aptitude questions
zoho aptitude questions 2019 pdf
zoho c aptitude questions with answers
c aptitude questions for zoho
zoho aptitude questions with answers
zoho c aptitude questions with answers pdf
zoho aptitude questions 2017 pdf
zoho digital marketing aptitude questions
zoho aptitude questions 2018 pdf
zoho technical support aptitude questions

diyaroy.com said...

Seeking for a Serious Relationship with Guwahati Call Girls
Looking for Call Girl in Guwahati to tie me up to the bed on my tummy
and put a condom on and rap me hard up the ass then turn me other tie me
up again spread my legs.Looking to build a relationship with a Guwahati
escorts that has a great heart to love a man , I'm not into anything one
night stand women Seeking Men for Today night.
Call Girls
Call Girls
Call Girls
Call Girls

Sarah Pilon said...

Smart City Lahore is going to be the best choice for commercial, investment and residential point of view. The scheme will have everything to attract national and international investors. In return, investors will get high revenue. On the other hand, the housing society is equipped with state of the art facilities. The facilities are just dream of come true for the people of Lahore. Peace, safety and eco-friendly behaviors. Future Development Holding hires and corporate’s with world-class developers, architectures and planners. This Smart City Lahore will have golf clubs and fields designed by experienced and world-recognized designers.

pkgiftshop said...

nice post credit recovery philadelphia

Deal and Delas said...

Lahore Park View City Location and Map
Real estate is one of the business sectors that is driven by some crucial points. For instance, in terms of property buying, location is one of the most important factors. In fact, most real estate experts define a location as one of the only factors that have the capacity to make or break the future valuation of the property. The Lahore PVC is a location wonder! Although there are many real estate projects located around this housing society, none of these housing schemes enjoys a location advantage like that of Lahore PVC.
Rudn Enclave payment plan
Blue world city Islamabad installment plan
park view lahore location

SEO said...

Delta overall selection affiliation is the best in class and unfeeling overseas employment agency in Pakistan. With inconceivable and competent HR structure. Our point of view is to give astonishing work associations. With our solid associations, we give able and gifted workers to different affiliations. We revolve around its customer's necessities as we work as indicated by the customer's sales. That is the explanation, Delta International is holding a solid typical relationship with by and large customers and outfit them with amazing and reliable associations.

Najaf Qureshi said...

I just visit your website and I found it very informative. Please share more content just like that. I want to read more content so please upload more articles. Thanks in advanced.

Packaging Host

Die Cut Stickers

Static Cling

Cheap Latest Products

Property Saga

Lahore Smart City

Nova City Islamabad

Park View City Islamabad

Al Noor Orchard Lahore

wow shayari said...

tntdrama activate

Unknown said...

Wow that was odd. I just wrote an incredibly long comment but after I
clicked submit my comment didn’t show up. Grrrr…

well I’m not writing all that over again. Regardless, just wanted
to say fantastic blog!


joellreyy87 said...

A feasible paper point is a vital aspect for planning an appropriate heading right from the beginning. The purchase assignment online composing specialists are prepared to offer you a decision of exposition titles and tests to set you on the right course with your exploration project.

Sabalanmusic said...

It was great
دانلود آهنگ جدید

Ramma Foundation Repair said...

If you're looking for a foundation repair Edmonton that you can trust, then look no further than Rammafoundation. We're a foundation repair Edmonton company that has been providing quality service to the community for over 20 years now. We understand the importance of quality work, and we're always dedicated to ensuring that our customers are happy and satisfied. We offer a wide range of services, and our team of experts is committed to providing the best possible results. Contact us today to learn more about our foundation repair Edmonton services!

SEO said...


akbet25 said...

วันนี้ทางเรา betflix เครดิตฟรี100 เทคนิคจริงของเกมสล็อต เว็บไซด์ betflix จะมาพูดถึงวิธีดารเอาชนะเกมสล็อตออนไลน์ อย่างง่ายๆ วิธี ดู สล็อตแตก เกมสล็อตออนไลน์ของค่าย pgslot ให้กับท่านดังนี้

Topline Marketing said...

In terms of real estate investments, Topline marketing always strives to provide quality guidance, services and consultancy regarding property management and investment opportunities. Housing projects like Prism Town Gujar Khan, New city Paradise and Blue World City sports Valley are the theme of the firm. Customers satisfaction is always kept on top priority.

Topline Marketing said...

We deals with top housing and commercial projects including Bahria Town Karachi 2 and Marshall Tower Peshawar etc. Customers satisfaction is our top priority.