1

I have a project which until recently was 100% ASP.NET MVC5 using Autofac as the DI. I now have a requirement to add a piece of Web API functionality so I have created a new Web API Project inside the solution to sit alongside the MVC project. I am intending to make use of the existing service layer which is in a third project.

My Autofac registration is all in the MVC project. I have spent most of today researching into using Autofac with Web API and I can see how to do it with stand-alone projects, and I can see how to do it with projects that are both MVC and Web API (answered in this SO question). But I can not see how I can set the DI container (built in the MVC project) as the DependencyResolver in the WebAPI project.

Is it possible to register a container across projects in this way?

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
WaltW
  • 41
  • 4
  • Won't the two apps be executing in different app domains / processes? If so, are you sure you really want it to share a DI container? – stephen.vakil Jan 06 '16 at 16:53

1 Answers1

2

Is it possible to register a container across projects in this way?

Probably.

But essentially the container configuration is for a single application. Sharing the configuration between 2 different applications is bound to have a lot of code that applies to one application or another, and some code that applies to both. This situation will likely make it difficult to understand and maintain the configuration code.

Think of it this way, the composition root of the application is the configuration of the application. You wouldn't share a web.config file between applications, so why would you want to share the DI configuration?

Of course, if you just add WebAPI to your existing application, you will prevent the need to have 2 different configurations because you will only have 1 application.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • I hadn't looked at it that way but that article makes a lot of sense. I'll consider adding WebAPI to the MVC project, but that was the original approach I started with and I had a different world of pain with Asp.NET Identity and cookies vs bearer token conflicts. – WaltW Jan 06 '16 at 17:44