Dependency Resolution in Web API
The new Web API feature (refer to Chapter 11) also includes the ability to support dependency resolution. The design of the dependency resolver in Web API is slightly different from the one in MVC but, in principle, serves the same purposes: to allow developers to easily get dependency injection for their controllers, as well as making it easy to provide services to Web API that are themselves created via dependency-injection techniques.
There are two significant differences in the dependency resolution implementation in Web API. First, there are no static APIs for default registration of services; these old static APIs in MVC were there for historical reasons. Instead, there is a loosely typed service locator that can be accessed at HttpConfiguration.Services, where developers can enumerate and replace the default services used by Web API.
Second, the actual dependency resolver API has been modified slightly to support the notion of scopes. One criticism of the original dependency resolver interface in MVC was the lack of any kind of resource-cleanup mechanism. After consultation with the community, we landed on a design that used the concept of a scope as the way that Web API would trigger this cleanup. The system automatically creates a new scope per request, which is available as an HttpRequestMessage extension method named GetDependencyScope. Like the dependency resolver interface, the scope interface has both GetService and GetServices methods; ...
Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.