Setting up Ninject with the new WCF Web API

So I've been playing around with the latest release of the WCF Web API and decided I wanted to dive into implementing Ninject with it.

Based off what I've read I need to implement the interface IResourceFactory which demands the following methods:

    public object GetInstance(System.Type serviceType, 
                              System.ServiceModel.InstanceContext instanceContext,
                              System.Net.Http.HttpRequestMessage request);

    public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext,
                                object service);

So I chicken scratched the following out:

public class NinjectResourceFactory : IResourceFactory
{
    private readonly IKernel _kernel;

    public NinjectResourceFactory()
    {
        var modules = new INinjectModule[]
                          {
                              new ServiceDIModule(),    //Service Layer Module
                              new RepositoryDIModule(), //Repo Layer Module
                              new DataServiceDIModule()
                          };

        _kernel = new StandardKernel(modules);
    }

    #region IResourceFactory Members

    public object GetInstance(Type serviceType,
                              InstanceContext instanceContext,
                              HttpRequestMessage request)
    {
        return Resolve(serviceType);
    }

    public void ReleaseInstance(InstanceContext instanceContext, object service)
    {
        throw new NotImplementedException();
    }

    #endregion

    private object Resolve(Type type)
    {
        return _kernel.Get(type);
    }

    //private T Resolve()
    //{
    //    return _kernel.Get();
    //}

    //private T Resolve(string name)
    //{
    //    return _kernel.Get(metaData => metaData.Has(name));
    //    return _kernel.Get().Equals(With.Parameters.
    //                                   ContextVariable("name", name));
    //}
}

and wired it up with

var configuration = HttpHostConfiguration.Create().SetResourceFactory(new NinjectResourceFactory());
     RouteTable.Routes.MapServiceRoute("States", configuration);

Amazingly, this seems to work. The first resource method I created to serve out a list of states/provinces generates output with HTTP 200 OK.

So, to the question. Is there a cleaner way of writing this factory? I really fuddled through it and it just doesn't feel right. I feel like I'm missing something obvious staring me in the face. The hack I made in the new Resolve method feels especially dirty so I figured I'd tap into those more experienced to tighten this up. Has anyone else implemented Ninject with the WCF Web API and implemented a cleaner solution?

Thanks for any input!

7
задан Alexander Zeitler 2 October 2011 в 11:32
поделиться