Lessons in this course (10)

8. Dependency injection, bundling, Identity and Web API 2 in MVC 5

Intermediate★ Must knowLesson 8 of 10

Dependency injection — MVC 5 has no built-in container; plug one in through DependencyResolver:

csharp
// Unity.Mvc5 — App_Start/UnityConfig.cs
public static void RegisterComponents()
{
    var container = new UnityContainer();
    container.RegisterType<ShopDbContext>(new PerRequestLifetimeManager());
    container.RegisterType<IProductService, ProductService>();
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}

(Autofac: builder.RegisterControllers(...), DependencyResolver.SetResolver(new AutofacDependencyResolver(container)).)

Bundling and minification:

csharp
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css", "~/Content/site.css"));
BundleTable.EnableOptimizations = true;   // or compilation debug="false" in web.config

ASP.NET Identity + OWIN: Startup.Auth.cs configures cookie authentication (UseCookieAuthentication), external logins (Google, Microsoft), UserManager/SignInManager with EF tables (AspNetUsers, AspNetRoles); [Authorize(Roles = "Admin")] protects actions.

Web API 2 in the same project: ApiController classes under /api/..., configured in WebApiConfig.Register (config.MapHttpAttributeRoutes()), returning data with content negotiation (JSON/XML). MVC and Web API 2 have separate pipelines, filters and DI resolvers in .NET Framework — ASP.NET Core unifies them.