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);
            }
        }
  • 相关阅读:
    集中式(SVN)和分布式(Git)版本控制系统的简单比较
    Mac 提示安装包已损坏
    React 获取 url 参数 —— this.props.match
    编写一个 Chrome 浏览器扩展程序
    webpack 配置学习笔记
    Python 进阶学习笔记
    Python 入门学习笔记
    (转)Unity3d各种坑
    unity3d 网页游戏客户端工程构建方案
    (转)在Unity3D的网络游戏中实现资源动态加载
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/10783151.html
Copyright © 2011-2022 走看看