Autofac Webapi 的依赖注入

前端之家收集整理的这篇文章主要介绍了Autofac Webapi 的依赖注入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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;
        }

}

谢谢

猜你在找的设计模式相关文章