作者:lululove8_530 | 来源:互联网 | 2023-09-17 16:42
一、安装Nuegt:Autofac.Mvc5二、添加服务类IProductServicenamespaceNewCmp.Services{publicinterfaceI
一、安装
Nuegt : Autofac.Mvc5
二、添加服务类
IProductService
namespace NewCmp.Services
{public interface IProductService{void Add();}
}
ProductService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;namespace NewCmp.Services
{public class ProductService : IProductService{public void Add(){}}
}
三、Global.asax.cs
using Autofac;
using Autofac.Integration.Mvc;
using NewCmp.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;namespace NewCmp
{public class MvcApplication : System.Web.HttpApplication{protected void Application_Start(){var builder = new ContainerBuilder();// Register your MVC controllers. (MvcApplication is the name of// the class in Global.asax.)builder.RegisterType().As();builder.RegisterControllers(typeof(MvcApplication).Assembly).InjectActionInvoker().PropertiesAutowired() ;// OPTIONAL: Register model binders that require DI.builder.RegisterModelBinders(typeof(MvcApplication).Assembly);builder.RegisterModelBinderProvider();// OPTIONAL: Register web abstractions like HttpContextBase.builder.RegisterModule();// OPTIONAL: Enable property injection into action filters.builder.RegisterFilterProvider();builder.RegisterType().As();// Set the dependency resolver to be Autofac.var container = builder.Build();DependencyResolver.SetResolver(new AutofacDependencyResolver(container));AreaRegistration.RegisterAllAreas();FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);}}
}
运行效果: