WebAPI2 uses the AutoFac dependency injection solution ., Webapi2autofac
There are few articles about the complete solution that can be found in Baidu by injecting dependencies on WebApi2, and there is no arm or leg break.
It is different from MVC5 dependency injection and should be noted in the annotations. Global Code on:
Namespace S2S. webApi {public class WebApiApplication: System. web. httpApplication {protected void Application_Start () {// ---- AutoFac DI ------ var builder = new ContainerBuilder (); SetupResolveRules (builder); builder. registerApiControllers (Assembly. getExecutingAssembly (); // RegisterApiControllers method var container = builder. build (); HttpConfiguration config = GlobalConfiguration. configuration; // note that the config object of the HttpConfiguration class must not be new. You must obtain the config from GlobalConfiguration. dependencyResolver = (new AutofacWebApiDependencyResolver (container); // note that this is different from MVC dependency injection // ----------------------------------------------------- AreaRegistration. registerAllAreas (); FilterConfig. registerGlobalFilters (GlobalFilters. filters); RouteConfig. registerRoutes (RouteTable. routes); BundleConfig. registerBundles (BundleTable. bundles); AreaRegistration. registerAllAreas (); GlobalConfiguration. configure (WebApiConfig. register); FilterConfig. registerGlobalFilters (GlobalFilters. filters); RouteConfig. registerRoutes (RouteTable. routes); BundleConfig. registerBundles (BundleTable. bundles );} /// <summary> /// AutoFac /// </summary> /// <param name = "builder"> </param> private static void SetupResolveRules (ContainerBuilder builder) {var assembly = Assembly. load ("s2s. BLL "); // load the Assembly builder according to the Assembly name. registerAssemblyTypes (assembly ). singleInstance (); // returns the same instance builder every time. registerAssemblyTypes (assembly ). where (t => t. name. endsWith ("Service ")). asImplementedInterfaces ();}}}
There is not much to explain. The Controller still uses constructor injection. It is already in the development test.
You can add it to favorites and view it later.