The short version is: You're in a Web API project but you're trying to use the MVC dependency resolver. You haven't set up the MVC dependency resolver anywhere in the demo project.
When your event handler calls DependencyResolver.Current.GetService<Foo>();
it's going to use the default MVC dependency resolver, not Autofac.
public class WebApiApplication : HttpApplication {
protected void Application_Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<Foo>().AsSelf().InstancePerLifetimeScope();
var container = builder.Build();
// Here's where the Web API resolver is set up...
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
protected virtual void Application_AcquireRequestState(object sender, EventArgs e) {
// ...but this call is using the MVC dependency resolver!
var foo = DependencyResolver.Current.GetService<Foo>();
}
}
If you look at what the System.Web.Mvc.DependencyResolver.DefaultDependencyResolver
does, it calls Activator.CreateInstance(type)
on the type requested. In this case, your Foo
type.
So - you will get two different instances because your dependency resolvers aren't set up correctly.
If you want to use the MVC dependency resolver, you're free to do that by setting it up per the documentation. Note that this will share the container, but not the request lifetime scope mechanism. If a Web API request comes in, it does not necessarily create a request lifetime scope in the same way as MVC so per-request dependencies will not work the way you think. There is a different mechanism to handle request lifetimes in Web API and that's also in the docs.
If you are using the non-OWIN Web API stuff, you can call GlobalConfiguration.Configuration.DependencyResolver
to get the Web API dependency resolver, which you have set up with Autofac. You can't get the per-request scope from this, though, nor can you resolve per-request dependencies. But if you have to manually resolve a service, that's how you'd do it.
If you choose to switch to OWIN Web API, there is no global configuration or global dependency resolver. You'll then be forced to make use of the DependencyScope
attached to a request message or make use of a mechanism like CommonServiceLocator
.