zoukankan      html  css  js  c++  java
  • MVC autofac 属性注入

    Global文件

    public class MvcApplication : System.Web.HttpApplication
        {
            private static IContainer Container { get; set; }
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
    
                var builder = new ContainerBuilder();
                //根据名称约定(服务层的接口和实现均以Contract结尾),实现服务接口和服务实现的依赖
                builder.RegisterAssemblyTypes(Assembly.Load("BLOG.IBLL"), Assembly.Load("BLOG.BLL")).Where(t => t.Name.EndsWith("Contract")).AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency();
                // 根据名称约定(数据访问层的接口和实现均以Repository结尾),实现数据访问接口和数据访问实现的依赖
                builder.RegisterAssemblyTypes(Assembly.Load("BLOG.IDAL"), Assembly.Load("BLOG.DAL")).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces().PropertiesAutowired().InstancePerDependency();
                builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
                Container = builder.Build();
                DependencyResolver.SetResolver(new AutofacDependencyResolver(Container));
            }
        }

    控制器

    public class DefaultController : Controller
        {
            //属性自动注入
            public IProvinceContract ProvinceContract { get; set; }
            // GET: Default
            public ActionResult Index()
            {
                return View();
            }
            public ActionResult GetProvinceList()
            {
                var list = ProvinceContract.GetList(p => p.Id > 0);
                return Json(list);
            }
        }
    PropertiesAutowired 属性注入

    IBLL

    public interface IProvinceContract
        {
            /// <summary>
            /// 获取列表
            /// </summary>
            /// <param name="where"></param>
            /// <returns></returns>
            IQueryable<Province> GetList(Expression<Func<Province, bool>> where);
        }

    BLL

     public class ProvinceContrator: IProvinceContract
        {
            //属性自动注入
            public IProvinceRepository ProvinceRepository { get; set; }
            public IQueryable<Province> GetList(Expression<Func<Province, bool>> where)
            {
                return ProvinceRepository.GetList(where);
            }
        }
  • 相关阅读:
    java如何手动创建一个线程池
    HashMap的面试总结(摘抄)
    JDK源码调试
    分布式和集群的区别
    开发中model,entity和pojo的区别
    java并发编程_CountDownLanch(倒计数锁存器)应用场景
    Map 怎么排序
    java中Thread的 interrupt异常处理
    zookeeper节点失效重连机制
    java并发库_并发库知识点整理
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/10783151.html
Copyright © 2011-2022 走看看