This project is read-only.

RegisterPerWebRequest AND RegisterWebApiRequest for the same IExampleService

Jul 27, 2014 at 3:25 PM
I have an ASP.NET web application that has both MVC5 and WebApi2 controllers. I would like my services to have a Lifestyle of "per X request" regardless of what controller they're injected into. I realize that MVC and WebApi controllers are very different things.

Is this possible out of the box or do I have to create two Container classes (one with RegisterPerWebRequest and the other with RegisterWebApiRequest) and register everything independently?

Thank you!
Jul 27, 2014 at 3:39 PM
Edited Jul 27, 2014 at 3:52 PM
I always advice against mixing MVC and Web API in the same project. Splitting up projects will remove the problem altogether.

If, for whatever reason you need to keep the projects together, another option is to give them each their own container instance, which allows the two technologies to run in more isolation in the same app domain.

A third option is to create a hybrid lifestyle as follows:
var apiLifestyle = new WebApiRequestLifestyle();
ScopedLifestyle hybrid = Lifestyle.CreateHybrid(
    () => apiLifestyle.GetCurrentScope(container) != null,
    new WebRequestLifestyle());
Now you can register your IExampleService with the hybrid lifestyle:
container.Register<IExampleService, ExampleServiceImpl>(hybrid);
Marked as answer by dot_NET_Junkie on 8/11/2014 at 12:10 PM
Jul 27, 2014 at 3:51 PM
Thank you for the quick response. We'll have to go with option 2 or 3.