Autofac可以对代码进行依赖注入,实现控制反转。以下是本菜鸟在初次入门时的代码配置,其源码,内部原理都还有待日后研究。目前也只是仅仅做到了能够使项目正常使用而已。

跟我一样刚刚入门的菜鸟朋友们可以借鉴一下。

一、使用NuGet进行引用添加

  1. Autofac 4.9.3

  2. Auto.Mvc5 4.0.2

二、Global.asax.cs 配置  

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);


            //配置AutoFac
            var builder = new ContainerBuilder();

            //把当前程序集中的Controller都注册 ->需要安装AutoFac.Mvc5
            builder.RegisterControllers(typeof(MvcApplication).Assembly)
                .PropertiesAutowired();

            //注册Serivce 加载Service所在的程序集
            Assembly[] assemblies = new Assembly[] { Assembly.Load("Ant.Crm.Admin") };
            //条件:只注册继承了BaseService的Service
            builder.RegisterAssemblyTypes(assemblies).Where(type=>!type.IsAbstract && typeof(BaseService).IsAssignableFrom(type));

            var container = builder.Build();

            //注册系统级别的DependencyResolver,这样当MVC框架创建Controller等对象的时候都是管Autofac要对象 !!!
            //->需要安装AutoFac.Mvc5。
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }

目录结构:

AutoFac的简单使用教程 

三、使用

1. 依照配置,需要将所有的Service都继承自BaseService,如图:

AutoFac的简单使用教程

2. 在Controller中使用已经注册到Autofac中的Service(构造器注入),如图:

AutoFac的简单使用教程 AutoFac的简单使用教程

 

OK,这就是Autofac的简单使用,以上为本人的学习笔记,仅供参考,如有错误,欢迎纠正。

 

喜欢本文章的朋友,欢迎关注公众号【程序员在职场】支持一下小编。

 AutoFac的简单使用教程

 

相关文章:

  • 2021-12-20
  • 2022-02-24
  • 2022-12-23
  • 2021-12-10
  • 2021-11-30
  • 2021-12-03
  • 2021-11-28
  • 2021-04-09
猜你喜欢
  • 2021-11-17
  • 2021-09-15
  • 2021-12-29
  • 2021-10-23
  • 2021-12-06
  • 2022-01-04
  • 2021-07-29
相关资源
相似解决方案