ASP.NET MVC IOC 之 Autofac(三)-webform中应用
在webform中应用autofac,只有global中的写法不一样,其他使用方式都一样
nuget上引用:
global中的写法:
private void AutoFacRegister() { var builder = new ContainerBuilder(); //注册MVC控制器(注册所有到控制器,控制器注入,就是需要在控制器的构造函数中接收对象) // builder.RegisterControllers(typeof(MvcApplication).Assembly); // builder.RegisterControllers(Assembly.GetExecutingAssembly()); //增加属性注入 // builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //可选,注册模型绑定 //builder.RegisterModelBinders(typeof(MvcApplication).Assembly); //builder.RegisterModelBinderProvider(); //可选,注册web抽象层例如HttpContextBase //builder.RegisterModule<AutofacWebTypesModule>(); //可选,启用视图页属性注入 //builder.RegisterSource(new ViewRegistrationSource()); //可选,启用方法参数注入 //builder.InjectActionInvoker(); /*接口实现*/ builder.RegisterType<StudentService>().As<IStudentService>().PropertiesAutowired(); //builder.RegisterType<TeacherService>().As<ITeacherService>().PropertiesAutowired(); //注册所有实现了 IDependency 接口的类型 Type baseType = typeof(IDependency); Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray(); builder.RegisterAssemblyTypes(assemblies) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsSelf().AsImplementedInterfaces() .PropertiesAutowired().InstancePerLifetimeScope(); //设置依赖解析器 // var container = builder.Build(); // DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); _containerProvider = new ContainerProvider(builder.Build()); }
使用方式:
public partial class Default : System.Web.UI.Page { public IStudentService _stu { get; set; } protected void Page_Load(object sender, EventArgs e) { Response.Write(_stu.GetStudentAge("张三")); } }