mvc

   MVC服务

Autofac 控制反转容器
先下载 Autofac dll,
web.config 配置
iis6
    <httpModules>

      <add name="ContainerDisposal" type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web" />

    </httpModules>

    <modules>

      <!--ii7 配置ioc-->

      <add name="ContainerDisposal"

            type="Autofac.Integration.Web.ContainerDisposalModule,Autofac.Integration.Web"

           />

    </modules>

var builder = new ContainerBuilder();
builder.RegisterType 注册类型
builder.Register 以Lampda方式注册
builder.RegisterInstance 注册对象


在mvc Global  添加如下

  

  public class MvcApplication : System.Web.HttpApplication,IContainerProviderAccessor

    {

        static IContainerProvider _containerProvider;

        public IContainerProvider ContainerProvider

        {

            get { return _containerProvider; }

        }





           





        public static void RegisterGlobalFilters(GlobalFilterCollection filters)

        {

            filters.Add(new HandleErrorAttribute());

        }



        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");



            routes.MapRoute(

                "Default", // Route name

                "{controller}/{action}/{id}", // URL with parameters

                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

            );



        }



        protected void Application_Start()

        {

          //  Assembly dll = Assembly.LoadFrom(System.Web.HttpContext.Current.Server.MapPath(@"bin\Shop.Data.Server.dll"));



            var builder = new ContainerBuilder();



            SetupResolveRules(builder);



         builder.RegisterControllers(Assembly.GetExecutingAssembly());



         



            _containerProvider = new ContainerProvider(builder.Build());



            ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(_containerProvider));



            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);

            RegisterRoutes(RouteTable.Routes);



            

        }





        private void SetupResolveRules(ContainerBuilder builder)

        {

             //ioc 控制器反转





       //     builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())

       //.Where(t => t.Name.EndsWith("Repository"))

       //.AsImplementedInterfaces();



           // builder.RegisterType<MessageRepository>().As<IMessageRepository>(); 第二种注册方法





            Assembly dll = Assembly.LoadFrom(System.Web.HttpContext.Current.Server.MapPath(@"bin\Shop.Data.Server.dll"));

            builder.RegisterAssemblyTypes(dll).Where(p => p.Name.EndsWith("Repository")).AsImplementedInterfaces();

           



   

 

        }





       

    }

  

dll 要与项目放在同一目录

你可能感兴趣的:(mvc)