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;
        appHost.PreRequestFilters.Add(this.PreFilter);
    }

    /// <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.

17 comments:

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.

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...


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

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.

wow shayari said...

tntdrama activate

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.

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!

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.

Ali Rad said...

nice blog thanks ^_^
شاهین بنان
ماکان بند
مجید رضوی

tomburke said...

embroidery digitizing services said...
Extending ServiceStack allows for unparalleled flexibility and customization in building robust and efficient web services. With its comprehensive framework and an array of features, ServiceStack paves the way for seamless integration of various functionalities, making it a top choice for developers. Whether you're enhancing data handling, creating cutting-edge APIs, or optimizing performance, ServiceStack empowers you to craft tailored solutions that meet the unique demands of your projects. Its extensibility is the key to unlocking the full potential of web services, promising a smoother development experience and unparalleled scalability.

cynthiarose said...

Impressed to hear about your positive experience with ServiceStack! Using plugins to preprocess the request pipeline is a really powerful solution that allows you to seamlessly add applications like IMerchant Token Service and elegantly manage HTTP headers. I'm glad I found an effective way to meet your needs. I also found such a site related to the best English language topics. If anyone has any ideas please let me know.

westcoastwatersafety said...

If you're in need of Lifeguards for hire western australia, we've got you covered! Our lifeguard services are second to none, providing you with peace of mind knowing that your aquatic facility or event is in safe hands. Our lifeguards are not only trained in water rescue techniques, but they also possess excellent communication and customer service skills, ensuring a positive and enjoyable experience for all patrons.

So whether you're hosting a pool party, operating a beachfront resort, or managing a public swimming pool, our lifeguards are ready to provide the highest level of safety and professionalism.

TelePort ManPower & Consulting said...

Perhaps the best programming tip for those who are using servicepack for their projects. It will for sure help them in their endeavors.
top recruitment agencies in Pakistan for Saudi Arabia