Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am hosting an web api which exposes a few REST services in a windows service. Since this is a windows service I use the HttpSelfHostServer class to host the api. Does anybody has any exprience on how to integrate an autofac IoC with self hosted web api. I know there is an integraion nuget package when using IIS to host the api but I could not find anything for self-hosted scenarios. Any advice will be appreciated.

Uros
Posted

1 solution

I found the solution to my problem. Actualy the steps needed are almost the same as when setting the autofac with web api hosted in the IIS. So to set-up the autofac with the self-hosted web api follow the next steps:

- download the Autofac.WebApi nuget package
- set the the autofac builder as you normally would
- the only difference is whan you have to assign the autofac as a dependency resolver to the web api. GlobalConfiguration is not accessible in the self-hosted scenario so you just use the DependencyResolver property on the HttpSelfHostConfiguration instance:

C#
var builder = new ContainerBuilder();
//Register the API controllers and other types as you normally would

var container = builder.Build();
var resolver = new AutofacWebApiDependencyResolver(container);
var config = new HttpSelfHostConfiguration(@"http://localhost:9099");
config.DependencyResolver = resolver;
var server = new HttpSelfHostServer(config);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900