WCF Web API with Web Activator package

In these days, I had read some blogs and a lot of post in internet about WCF Web API. And I also have curious about it.  It is not new technology. And after I watched some postcast. I recognize it is a good one that I must to researching. RESTfull is a hot topic and have a lot of argues these days. WCF Web API is built on top of WCF service. How does it good? I don't know we just follow and analyze it later. Do you agree with me?

As you know, if you host WCF service to a IIS host, and you want to use IoC inside it. You must to customize some classes in WCF factory to do it, or you can add Global.asax file and try to override the start method for register all things you need. When .NET 4 came to us, it brought with a new technology for start application, that mean you don't need to customize WCF factory or add Global.asax file. As me, we only need to customize WCF when we have a special case on it, for example we need to filter action, AOP on WCF for logging, exception management. So what is technical I use for? Hm...hm. The first thing we need to config the WCF service first. We just open Visual studio and add WCF servce project. It's easy, isn't it? So I will don't mention this step here. Second step is add some packages from NuGet command. And I also don't mention about how do you add this with NuGet? You can find on google for this. A few of packages that you need to add are WebApi.Core, WebActivator, Autofac, CommonServiceLocator. You can see we add WebActivator pakage, this is a package that we need for start the application. And after that I add a class called AppStart.cs. Content of it is here:

[assembly: WebActivator.PreApplicationStartMethod(typeof(AppStart), "Start")]

namespace SampleService
{
    public static class AppStart
    {
        public static void Start()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<SampleResouce>();
            builder.RegisterType<ResourceProvider>().As<IResourceProvider>();

            var container = builder.Build();

            ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(container));

            var configuration = HttpHostConfiguration.Create().SetResourceFactory((t, i, r) => container.Resolve(t), null);

            RouteTable.Routes.MapServiceRoute<SampleResouce>("categories", configuration);
        }
    }
}

I use PreApplicationStart method in Web Activator for start application. I set up  Autofac container, register it and assign it to Microsoft Common Service Locator. And filnally I map it to WCF Web API for register Routing service. That's it.

Because I use Autofac for IoC container, so I add a class with named is ObjectFactory.cs:

    internal static class ObjectFactory
    {
        public static TService GetService<TService>()
        {
            return ServiceLocator.Current.GetInstance<TService>();
        }
    }

This class is simple. If you want more methods for resolve the object. Please at here. I just keep it simple. 

To demostrate about dependency injection, I add a stub class for providing all resources for WCF service.

    internal interface IResourceProvider
    {
        List<string> GetAllString();
    }
    internal class ResourceProvider : IResourceProvider
    {
        public List<string> GetAllString()
        {
            return new List<string> { "Books""Fruit" };
        }
    }

Finally, we have a WCF service with web api like this: 

    [ServiceContract]
    internal class SampleResouce
    {
        private readonly IResourceProvider _resourceProvider;

        public SampleResouce()
            : this(ObjectFactory.GetService<IResourceProvider>())
        {
        }

        public SampleResouce(IResourceProvider resourceProvider)
        {
            _resourceProvider = resourceProvider;
        }

        [WebGet(UriTemplate = "")]
        public List<string> GetAllString()
        {
            return _resourceProvider.GetAllString();
        }


        [WebGet(UriTemplate = "{item}")]
        public string GetString(string item)
        {
            return item;
        }
    }

You can see I have a method for get all strings and one method for get string by name. Because it is RESTful so you can access it in your url. You only need to type like this http://localhost:xxxx/categories or http://localhost:xxxx/categories/books and see what happen. (xxxx is a port that your application is host in) Look good and clean, isn't it? Hope my post will make you happy about register and use WCF Web API and Web Activator. Do you have any suggestion for improve my post?

You can get a source code at here

Shout itkick it on DotNetKicks.com

6 Comments

  • Good points. How do you go about using the WCF Web API in ASP.NET MVC with routing integrated with MVC routing?

  • Hi Jay,

    I think you can see the presentation from Glenn Block about WCF Web API at http://channel9.msdn.com/events/MIX/MIX11/FRM14. He describe very clear about how can you create WCF Web API for ASP.NET MVC project and how do you register a routing table with ASP.NET MVC.

  • I am very excited by getting this article, coding part is always tough to describe in effective manner but this article has done a great job.

  • Pretty part of content. I just stumbled upon your web site and in accession
    capital to assert that I get actually loved account your weblog posts.

    Any way I will be subscribing for your augment and even I fulfillment
    you get admission to constantly fast.

  • Every weekend i used to pay a visit this web page, because i
    wish for enjoyment, for the reason that this this website conations genuinely fastidious funny
    stuff too.

  • What's up, everything is going sound here and ofcourse every one is sharing facts, that's truly good, keep up writing.

Comments have been disabled for this content.