Autofac在.net mvc下的配置和使用

1.环境:.netframework 

 

2.基本使用逻辑:

基本使用分两步考虑:(1)控制器的注册   (2)业务类的注册

业务类注册基本操作:

在接口中定义一个标识接口,其他的接口都继承自这个接口,利用容器将继承和实现这个接口的类注册。

 

3.具体实现过程

(1)在MVC项目中安装Autofac.mvc程序包    即:Install-Package Autofac.MVC5

(2)在MVC项目Global.asax文件添加如下代码:其中Service为本例业务类命名空间   IServiceSupport为定义的标识接口

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var builider = new ContainerBuilder();
            builider.RegisterControllers(typeof(MvcApplication).Assembly)
                .PropertiesAutowired();//把当前程序集中的Controller都注册


            ///获取所有相关类库的程序集  Load()参数就是要加载程序集名称
            Assembly[] assemblies = new Assembly[] { Assembly.Load("Service") };
            builider.RegisterAssemblyTypes(assemblies)
                //进行类型过滤   type1..IsAssignableFrom(type2)表示type1类型是否可以指向type2类型的对象
                //放到此处即  将继承和实现IServiceSupport接口的类注册  避免注册无关的类
                //IServiceSupport接口定义在IService类库项目中接口中无任何定义   主要作用就用在此处
                .Where(type => !type.IsAbstract && typeof(IServiceSupport).IsAssignableFrom(type))
                .AsImplementedInterfaces()
                .PropertiesAutowired();

            var container = builider.Build();
            //注册系统级别的  DependencyResolver 这样当MVC框架创建Controller等对象时都像Autofac要对象
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

 

4.如出现 未能加载文件或程序集“xxx”或它的某一个依赖项。系统找不到指定的文件。测试MVC项目没有添加对业务类项目或者接口项目的引用。 

 

5.项目源码链接:https://pan.baidu.com/s/17nZJKMTIU5dG5xIMF49TbQ 
提取码:9xom

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值