NHibernate session management in the WCF Web API

As the WCF Web API project is a bit of a moving target at the moment, it’s been hard to try and find a sensible way to handle NHibernate sessions for each resource. They key word there is resource.

If you’ve ever used NHibernate with WCF before, you’ve probably organised your session management around the per-request model. That starts to break down with WCF Web APIs. You see, you have to consider how OData is consumed. This is where you have a resource operation that returns an IQueryable<T> that is evaluated after the operation returns. This is a really cool thing, but it breaks if you use a per-request style management method, or if you manually open and close the session for each operation. For example:

[ServiceContract]
public class MyResource
{

    private ISessionManager _sessionManager;
    private IWidgetRepository _widgetRepository;

    // You always inject, right?...
    public MyResource(ISessionManager s, IWidgetRepository r)
    {
        _sessionManager = s;
        _widgetRepository = r;
    }

    [WebGet(UriTemplate = "dtos")
    public IQueryable<MyDTO> GetAllMyDTOs()
    {
        using(_sessionManager.GetSession())
        {
            return _widgetRepository.Query();
        }
    }
}

This is bad/wrong/silly. As the response from GetAllMyDTOs isn’t actually evaluated until after the operation returns, it will fail, as you’ve disposed the session it’s linked to.

The other, “worserer” way is to just wait until the garbage collector cleans up your session by itself. I shouldn’t have to explain why that’s a monumentally stupid thing to do.

So, I had a bit of a think about this problem. While there is the option of message handlers and operation handlers, they still don’t give you a way of executing some code before and after an operation (to open and close the session). On top of that, operation handlers are asynchronous, so if you’re being good and binding your session to a ThreadStatic variable, it won’t be bound to the same thread your operation will actually execute on.

If you’re using dependency injection to build your resources (which you should), then you’ve no doubt used the WebApiConfiguration class and created a method on your class to handle the CreateInstance delegate. This method would locate the requested type in your DI container and return the composed instance.

Well, there’s a corresponding delegate exposed by WebApiConfiguration called ReleaseInstance. It’s job is to take an instance and get rid of it.

Now we have two methods, fired at each end of a resource’s life-cycle. The only concern I had is if, somehow, the create/release methods ran on a different thread to the operation. So I stuck a little logging of the thread ID in there and did a couple of tests. Same thread ID all around! Not only that, each subsequent quasi-simultaneous (because I can’t think of a better way to describe it) resource request utilised a different thread. At least, that’s the anecdotal evidence I’ve… anecdoted. So each resource would have it’s own session, as each session is bound to a ThreadStatic variable!

So, at the moment, I have a naïve implementation of session management, scoped per resource, that looks like this:

public class MyWebApi : System.Web.HttpApplication
{
    public void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathinfo}");

        var config = new WebApiConfiguration
                            {
                                EnableTestClient = true,
                                CreateInstance = Create,
                                ReleaseInstance = Release
                            };
        routes.SetDefaultHttpConfiguration(config);

        routes.MapServiceRoute<MyResource>("myresourceuri");
    }

    private object Create(Type t, InstanceContext c, HttpRequestMessage r)
    {
        var sm = Injector.Default.Get<ISessionManager>();
        sm.OpenSession();
        return Injector.Default.Get<t>();
    }

    private void Release(InstanceContext c, object i)
    {
        var sm = Injector.Default.Get<ISessionManager>();
        sm.CloseSession();
    }
}
Note: enabling the test client is fine, for testing. Make sure you disable it when you release, otherwise nasty people with bad haircuts and no friends will use it as an instructional guide to ruining your API.

 

As I said, this is a very simplified chunk of code. I haven’t load tested it sufficiently (read: at all) to be able to say with any Jobsian sense of confidence that it’s flawless. But it gives me the result I want at the moment. Until I find something better…

Posted in .NET Development | Tagged , , | Comments Off

How to get your WCF Web API DELETE verb working on IIS6

I’ve just had to deal with a problem on Windows Server 2003 (IIS 6.0) where my web API decided not to respond to the DELETE verb. Apparently, this is by design.

It doesn’t happen when you’re in development mode using the VS web server, so I didn’t catch it when I was developing. When I went to put it on the test server, deletes would fail. Fiddler would report a 501 Not Implemented error was returned by the server. I initially thought I’d messed up the resource mappings, but it wound up being the server configuration.

Your first response might be to head over to the application configuration on the server and simply add the missing verbs to the existing mappings. But WCF web APIs don’t have a file type, so there’s no mapping for you to edit!

To fix it, you need to setup a wildcard mapping on the server. A wildcard mapping allows you to specify an ISAPI handler that is run after every other mapping is attempted. It’s a kind of catch-all; hence the name.

Here’s how to set up a wildcard mapping:

  1. Open the IIS Manager snap-in.
  2. Use the treeview to navigate to the web site or application hosting your API.
  3. Right-click the application and select Properties.
  4. On the Virtual Directory tab, click the Configuration button.
  5. On the Mappings tab, click Insert next to the Wildcard application maps list.
  6. In the Executable text box, enter the path to the aspnet_isapi.dll version that your API is built for.
  7. Click OK to close the mapping dialog.
  8. Click OK to close the Application Configuration dialog.
  9. Click OK to close the properties dialog.
  10. Go delete something!

It’s not hard to fix the problem, in the end.

Posted in .NET Development, Tips | Tagged , , | Comments Off

Subclassed singleton instance

I couldn’t really think of a good explanatory title for this post, so I guess I’ll just have to explain. I’m setting up a dependency injection resolver using NInject, and I’m trying to centralise the implementation so it can be reused in the various layers of the application, but I want each application to be able to configure it in isolation of every other layer. I’m still not quite sure that I’m explaining what I want correctly, so let me try explaining it this way.

In App.Core. I want to create the InjectorBase class that every injection implementation derives from. Then, for example, in the App.UI I want to create a UserInterfaceInjector that descends from InjectorBase, but I only want the subclass to supply configuration. Then in App.Services I can create a ServicesInjector that also descends from InjectorBase, and again, only supplies configuration.

The next trick to this is, I want the dependency injection to be through a singleton. Yes, yes, singletons are evil etc. In this case, it’s being used for what I consider a correct purpose (as a service locator), and not some sort of global variable hold-all. So, in some random piece of code in App.Services, I want to be able to do something like this:

public void SomeMethodThatDoesSomethingTo(Some variable)
{
    var aRepository = ServicesInjector.Default.Get<IARepository>();
    aRepository.Add(variable);
}

And, conversely, in the App.UI I want to be able to do this:

public void SomeMethodThatLocatesAServiceImplementation()
{
    var aService = UserInterfaceInjector.Default.Get<IAService>();
    aService.DoSomethingMostLikelyAsynchronously();
}

It all seems fairly straight forward, yes? Well, it winds up not being too difficult, but one of the first problems you’ll run into relates to inheritance and the static keyword. Basically, you can’t. Which actually makes sense if you care to try and understand it. Anything static is of the class, not of an instance of the class. If you create a subclass, it’s new class, so the static thing doesn’t follow you. Why do we need the static keyword? The singleton. Here’s an example (simple) singleton implementation.

public class MySingleton
{
    private static MySingleton _default;

    public static MySingleton Default
    {
        get { return _default ?? _default = new MySingleton(); }
    }

    public string SayHello()
    {
        return "Hello!";
    }
}

In order to supply a reference to an instance without maintaining that reference in another class, we have to use a static field (to hold the reference) and a static property (to get at the static field).

Where I wanted to take this that was a bit out of the ordinary, is I wanted the singleton in the base class so implementors didn’t have to think about all that plumbing. This means making the base class abstract (so it can’t be directly instantiated) and then providing an abstract method that returns a container configuration. Then all the subclasses have to do is inherit from the base class and then provide an implementation of the abstract method.

The next problem is, the configuration method is an abstract method of the base class, and not static, but the point of creation of the class is in a static property get method. How do you call an instance method of a class to obtain configuration you need at creation time without an instance of the class? Well, you can’t. Now, obviously I’ve solved this problem, otherwise we’d be at the end of this post.

The gist of it involves breaking a cardinal rule of C# object creation: Don’t call virtual methods in a constructor. The reasoning behind this is C# initialisers (initializers for the Americans amongst us) run in order of farthest child back up to the base class, but the constructors run from the base class to the farthest child. Here’s a bit more information. The trick to overcoming the actual problem was to use the Activator class. This involves a bit of genericism of the base class to ensure the child class is being instantiated, which then allows us to call the virtual method with abandon. So the base class now looks like this:

abstract class BaseClass<T> : IHello where T: IHello
{
    private static IHello _default;
    private readonly string _message = "Hello from the base class.";

    public static IHello Default
    {
        get { return _default ??
                    (_default = Activator.CreateInstance<T>()); }
    }

    protected BaseClass()
    {
        _message = GetMessage();
    }

    public void SayHello()
    {
        Console.WriteLine(_message);
    }

    public abstract string GetMessage();
}

Here’s IHello, in case you couldn’t figure it out:

interface IHello
{
    void SayHello();
}

Finally, here’s how the implementors of the base class look:

class ChildClass : BaseClass<ChildClass>
{
    public sealed override string GetMessage()
    {
        return "Hello from the child class.";
    }
}

You can tie all this together in a console application with a bit of this magic:

class Program
{
    static void Main(string[] args)
    {
        ChildClass.Default.SayHello();
        Console.ReadKey(true);
    }
}

I’m about to roll this into the code. The spike seems to work without any problems (other than ReSharper warning me about my virtual method call in the constructor), but until I put it into the application code I won’t really know if it’s 100%. Let me know if you spot anything silly, won’t you?

Oh, here’s a link to the sample code if you want it.

Posted in .NET Development | Tagged , , , , | Comments Off

Resolving an existing instance with Ninject

Today I was looking for a way to allow a type to resolve to a specific instance that I had already created – something not known at the time the Ninject kernel is initialised. There is no method of a Ninject binding that explicitly handles this kind of thing.

The trick is to use the ToMethod method. ToMethod takes a lamda as a parameter. It’s defined as:

ToMethod(Func<IContext, IInstance> method)

This means ToMethod takes a function that accepts the injection context and returns an instance of the type being bound to. We can now use this to return our specific instance:

myKernel.Bind<IMyInstance>.To(context => anInstanceOfMyInstance);

The gotcha being that any Get of IMyInstance will result in a reference to the original anInstanceOfMyInstance. You have to be careful of lifetime, and therefore scope, and any changes to state.

I’m not convinced that this is actually a good idea, but it solves my immediate problem.

NInjectExistingInstanceTest

(And yes, this represents yet another return to blogging in some more regular form… I do intend to come through with the previously promised goods, just not in any specific order…)

Posted in Tips | Tagged , , | Comments Off

Gimp window focus

 

I’ve been using a combination of The Gimp and Inkscape to handle my artwork needs of recent. As I’m running them in OS X, they need to use the X11 environment. One of the annoyances I have been having with the Gimp is every window has needed an extra click just to focus it.

It turns out the fix is not difficult. I initially thought it might involve turning on the “focus follows mouse” option, but instead it was this:

X11 Preferences

So if you’re using an X11 application and find yourself dealing with weird focus issues, try turning on “Click-through Inactive Windows”. It did the trick for me.

 

Posted in Tips | Tagged , , , | Comments Off

Who gets it perfectly right the first time?

A roadsign on the way to Karatha, Western Australia.

There was an interesting argument I was a witness to a few days ago. The basic premise was, a developer was complaining about the lack of thought that went into a particular area of a particular piece of software.

He was right. The most basic amount of thought had been put into it, and the thought that had been put into it was wrong. It was causing him some distress (shall we say…) and the conversation was getting quite heated. Continue reading

Posted in Fundamentals | Tagged , , | 2 Comments

First blood!

Bee

Wow. I mean, I realise the whole point of putting something in the app store is to get it into other people’s hands, but wow. After finally getting the contracts sorted out (still a GST issue, but that’s a simple thing), LiveTrax Pro went live.

To be perfectly honest, I didn’t think (and really, I still don’t think) that there’s any kind of huge market for LiveTrax Pro. The “back-of-a-napkin” math went something like this. X million iPads sold (let’s say 10 – I know it’s more, but humour me…). Number of performers who own iPads would be X percent of that (let’s say 5% – 500k…). X percent of those would consider using their iPad live (let’s say 5% again – 25k…). Standard conversion rates for app sales are somewhere around 1%, so that leaves 250 people who may buy my app. But that’s not why I wrote it. Continue reading

Posted in LiveTrax Pro | Tagged , , , | Comments Off

Seal of Approval!

Cathedral in Bendigo

It appears I have been granted access to that exclusive club, the App Store. Today I received the fantastic news that LiveTrax Pro has been approved for sale!

Unfortunately, right now you won’t be able view it as I am still waiting on an ABN number before my contract is complete. If you think waiting for app approval from Apple can take a long time, trying getting something out of the Australian government…

Anyway,  good news for now. Time to fix up the websites while I’m waiting for my mark of the beast…

Posted in LiveTrax Pro | Tagged , | Comments Off

What’s coming up, or “Keeping myself honest”.

Hedge

In the interests of providing some impetus for myself, I thought I’d detail a few ideas of the posts I want to write. Some of them I’ve been wanting to write for a while, others are new ideas that have come about from my recent journey to the “other side” (read: Apple).

Writing like this is quite new for me, and I know that I’ll be more focused if I put myself under a little bit of pressure by detailing what I’m thinking about. As I write them, I’ll try and update the list to link to the specific articles. Continue reading

Posted in Blog | Tagged | Comments Off

LiveTrax Pro is pending review

Just a tree

After a little bit of mucking about, I’ve finally submitted my first application to the Apple App Store. (Hence the lack of posting for a few days…) I have to say, the process seems a little convoluted, but that’s most likely because of the need to grab a certificate to sign the code.

Now, in fairness to Apple, I did recently upgrade to XCode 4.0, which means that the instructions detailed in the iTunes Connect site weren’t aimed at me. It took me a little bit of mucking about to find some of the things that need to be found, and I’m pretty sure I’ve still not got the actual distribution build settings quite right. XCode 4.0 has some pretty cool features around build configuration that aren’t clear to me yet.

Anyway, now the long wait begins. They say their typical turn-around is about two weeks. All things considered, I’m expecting a fairly quick response and a rejection seeing as it’s my first submission. Let’s see how that pans out.

Posted in LiveTrax Pro | Tagged , , , | Comments Off