栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.NET MVC5+AUTOFAC实战

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.NET MVC5+AUTOFAC实战

这几天研究IOC容器、DI:
解耦,不用一个个实例化(理解到这了)面向接口编程思想

于是昨天实验了一把MVC中如何使用IOC、构造函数注入
话不多说上代码:
小框架一拉

展开细说

Model:

(懒的改名)

    public class Class1
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Grade { get; set; }
    }

仓储Resitory:

定义一个接口

   public  interface IStudentResitory
    {
        string GetName(int id);
    }

实现一个接口:

public   class StudentResitory:IStudentResitory
    {
        public string GetName(int id)
        {
            switch (id)
            {
                case 3:
                    return "yhf";
                case 4:
                    return "zjj";
                case 5:
                    return "jwz";
                default:
                    return "ddd";
            }
        }
    }

Service:

定义一个接口

用构造函数注入IStudentResitory

  public  class Service :IService
    {
        private readonly IStudentResitory _studentRepository;

        public Service(IStudentResitory studentResitory)
        {
            this._studentRepository = studentResitory;
        }
        public  string GetName(int id)
        {
            return this._studentRepository.GetName(id);
        }
    }

Ioc:


安装包Autofac

 public static  class MvcContainer
    {
        public static IContainer Instance;
        public static System.Web.Mvc.IDependencyResolver Init(Func func = null)
        {
            var builder = new ContainerBuilder();//新建容器用于注册组件
            MyBuild(builder);//注册组件
            func?.Invoke(builder);
            Instance = builder.Build();//利用构建器创建容器
            return new AutofacDependencyResolver(Instance);//返回针对MVC的解析器 
        }
        public static void MyBuild(ContainerBuilder builder)
        {
            //注册仓储层
            Assembly repositoryAssembly = Assembly.Load("Repository");
            builder.RegisterAssemblyTypes(repositoryAssembly)
                .PublicOnly()   //只要public访问权限的
                .Where(cc => cc.IsClass)    //只要class类型的(排除值和interface类型)
                .AsImplementedInterfaces(); //自动以其实现的接口暴露(包括Dispose接口)

            //注册逻辑层
            Assembly serviceAssembly = Assembly.Load("Service");
            builder.RegisterAssemblyTypes(serviceAssembly)
                .PublicOnly()
                .Where(cc => cc.IsClass)
                .AsImplementedInterfaces();

            Assembly MvcAssembly = Assembly.Load("CESHI");
            builder.RegisterControllers(MvcAssembly);//注册MVC项目中的Controller

        } 
    }

回到MVC项目中 Global.asax文件在编译的时候执行我们注册组件的方法

   protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            try
            {
                System.Web.Mvc.IDependencyResolver autofacResolver = MvcContainer.Init();
                DependencyResolver.SetResolver(autofacResolver);
            }
            catch (Exception ee)
            {

                throw new Exception(ee.ToString());
            }
        }

最后在我们HomeController中通过构造函数的方法依赖注入
注意也要安装AUTOFAC

  private readonly IService _service; 
        public HomeController(IService service)
        {
            this._service = service;
        }
        [HttpGet]
        public string GetNameById(int id)
        {
            return _service.GetName(id);
        }

注意配置config:

  
        
        
      

最终效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/905702.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号