.NET MVC5+AUTOFAC实战

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

于是昨天实验了一把MVC中如何使用IOC、构造函数注入
话不多说上代码:
小框架一拉
.NET MVC5+AUTOFAC实战
展开细说

Model:
.NET MVC5+AUTOFAC实战
(懒的改名)

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

仓储Resitory:
.NET MVC5+AUTOFAC实战
定义一个接口

   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:
.NET MVC5+AUTOFAC实战
定义一个接口
.NET MVC5+AUTOFAC实战

用构造函数注入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:

.NET MVC5+AUTOFAC实战
安装包Autofac

 public static  class MvcContainer
    {
        public static IContainer Instance;
        public static System.Web.Mvc.IDependencyResolver Init(Func<ContainerBuilder, ContainerBuilder> 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:

  <dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863AF14B0044DA" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-6.2.0.0" newVersion="6.2.0.0"/>
      </dependentAssembly>

最终效果

.NET MVC5+AUTOFAC实战

上一篇:使用Maven的assembly插件


下一篇:反射--程序集