nuget (一定是看好了,是WebApi2)
Install-Package Autofac.WebApi2 -Version 3.4.0
Application_Start
//Autofac var builder = new ContainerBuilder(); // Get your HttpConfiguration. var config = GlobalConfiguration.Configuration; SetupResolveRules(builder); // Register your Web API controllers. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // OPTIONAL: Register the Autofac filter provider. builder.RegisterWebApiFilterProvider(config); // Set the dependency resolver to be Autofac. var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
SetupResolveRules
private static void SetupResolveRules(ContainerBuilder builder) { builder.RegisterType<CustomersRepositorys>().As<ICustomersRepositorys>(); builder.RegisterType<CustomerServers>().As<ICustomerServers>(); }
In ApiController
public class CustomersController : ApiController { readonly ICustomersRepositorys _customersRepositorys; readonly ICustomerServers _customerServers; public CustomersController(ICustomersRepositorys customersRepositorys,ICustomerServers customerServers) { _customersRepositorys = customersRepositorys; _customerServers = customerServers; } }
谢谢