Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the disadvantage of using InstancePerHttpRequest instead of InstancePerApiRequest in MVC and Web API in same project?

My application is exactly like VS 2013's Web API default template. Basically, Web API 2 is for API, and MVC 5 is for documentation.

I'm using Autofac and so far it is working great. The following is the strip down version of what I have -

var builder = new ContainerBuilder();

var assemblies = Assembly.GetExecutingAssembly();
builder.RegisterControllers(assemblies);
builder.RegisterApiControllers(assemblies);

builder.RegisterType<MyService>().As<IMyService>()
   .InstancePerHttpRequest();

var apiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = apiResolver;

var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);

So far InstancePerHttpRequest works for both MVC and Web API.

Question

I'm wondering the disadvantage of using InstancePerHttpRequest instead of InstancePerApiRequest, so that I won't be surprised if I encounter a problem in the future.

I found similar question, but it did not answer my question.

Note: I found some answers in SO saying we should not mix MVC and Web API in same project. For me, I just need few MVC web pages for documentation, so I do not want to create new MVC project.

Thanks in advance!

like image 224
Win Avatar asked Mar 20 '23 18:03

Win


1 Answers

Right now, the InstancePerApiRequest and InstancePerHttpRequest methods do exactly the same thing - register InstancePerLifetimeScope with a common lifetime scope "name." It's effectively InstancePerMatchingLifetimeScope("AutofacWebRequest").

The request scope is named the same thing in web forms, WebAPI, and MVC integration so it's all interchangeable. This is intentional. But, since the challenge is that you can mix and match all of these, or use just one, we have to offer the "same thing" for each technology. There is talk on the forum of creating some sort of central/base "web integration" library that is common across all the ASP.NET stuff to remove confusion, but it'll be a breaking change so it won't happen for a while.

For the time being, you are safe using the two extensions interchangeably.

Note that the other extensions (e.g., InstancePerApiControllerType) do different things, so it's only the "request lifetime scope registration extensions" that are interchangeable.

like image 132
Travis Illig Avatar answered Apr 26 '23 12:04

Travis Illig