.net-4.0dependency-injectionautofacwcf-restwcf-4

Autofac + WCF REST 4.0


I am building a WCF 4.0 REST service and want to use Autofac as DI container. Apparently, I want to be able to call a parameterized constructor of the service class (service contract implementation), which accepts a bunch of interfaces to work with. Those interfaces are to be registered within Autofac container and I want them resolved and used when creating an instance of my service class (instead of calling not parameterized constructor, which is default).

There is similar problem with MVC controllers, which is solved by Autofac MVC Integration package. Is there anything ready-to-use for WCF REST 4.0? If no, what is the best way to solve my problem? E.g., is there anything like MVC's DependencyResolver which I can set up to use Autofac?

Note, that since 4.0 they changed some concepts in WCF REST. E.g., now there is no .svc file, routing is enough to call required method. I am quite new to WCF REST 4.0, so I wanted to ask community for suggestions before spending days on implementing some huge custom mechanism. Alas, quick search over internet did not provide me with an acceptable solution.


Solution

  • In your global application startup:

    //Build a container with your service registered.
    var builder = new ContainerBuilder();
    builder.RegisterType<YourService>();
    var container = builder.Build();
    
    //Set AutofacHostFactory.Container with this built container.
    AutofacHostFactory.Container = container;
    
    //Use AutofacWebServiceHostFactory instead of WebServiceHostFactory
    var factory = new AutofacWebServiceHostFactory();
    
    //Add your routes
    RouteTable.Routes.Add(new ServiceRoute("YourServiceUrl", factory, typeof(YourService)));
    

    That's all.