1. 程式人生 > 其它 >.net framework Autofac實現控制器屬性注入和過濾器屬性注入

.net framework Autofac實現控制器屬性注入和過濾器屬性注入

 

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ContainerBuilder builder = new ContainerBuilder();

            //實現控制器屬性注入的關鍵--PropertiesAutowired()
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();

            //實現過濾器屬性注入的關鍵
            builder.RegisterFilterProvider();

            //註冊類庫程式集
            builder.RegisterAssemblyTypes(Assembly.Load("Repository")).AsImplementedInterfaces().PropertiesAutowired();

            //註冊類庫程式集
            builder.RegisterAssemblyTypes(Assembly.Load("Services")).AsImplementedInterfaces().PropertiesAutowired();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ContainerBuilder builder = new ContainerBuilder();

            //實現控制器屬性注入的關鍵--PropertiesAutowired()
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();

            //實現過濾器屬性注入的關鍵
            builder.RegisterFilterProvider();

            //註冊類庫程式集
            builder.RegisterAssemblyTypes(Assembly.Load("Repository")).AsImplementedInterfaces().PropertiesAutowired();

            //註冊類庫程式集
            builder.RegisterAssemblyTypes(Assembly.Load("Services")).AsImplementedInterfaces().PropertiesAutowired();

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }