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);
            }
        }
  • 相关阅读:
    linux查看系统类型和版本
    javascript 中的继承实现, call,apply,prototype,构造函数
    redis原理分析
    HashTable 简述
    算法之 快速排序
    react js 之生命周期
    Java源代码编译过程
    Java字节码文件结构---概述
    Java程序运行时内存划分
    数据结构--汉诺塔--借助栈实现非递归---Java
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/10783151.html
Copyright © 2011-2022 走看看