Autofac 的简单配置

Autofac 的简单配置

注:博主自己学习构建项目的简单配置,博主小白不会太高深的

这里写图片描述
对于Auto我就不介绍了网上多的是

Auto下载及安装图解


这里写图片描述
这里写图片描述


Global.asax.cs添加一行配置代码

//控制反转,依赖注入配置
AutoFacConfig.Register();

AutoFacConfig配置代码

新建一个配置autofac的静态类,这样方便管理不乱

namespace MyMvc.App_Start
{
    public static class AutoFacConfig
    {
        public static void Register()
        {
            //构造一个AutoFac的builder容器  
            ContainerBuilder builder = new Autofac.ContainerBuilder();
            //从当前运行的bin目录下加载程序集  
            Assembly controllers = Assembly.Load("MyMvc");
            builder.RegisterControllers(controllers);
            SetDepend(builder);
            //创建一个真正的AutoFac的工作容器  
            var container = builder.Build();
            //移除原本的mvc的容器使用AutoFac的容器
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

        /// <summary>
        /// 依赖加载
        /// </summary>
        public static void SetDepend(ContainerBuilder builder)
        {
            //为什么要加载这两个DLL文件
            //凡是被接口引用方法的类库都要进行反射,对于common、model等不被接口引用到方法的则不需要
            //加载数据处理层程序集。  
            Assembly MyDAL = Assembly.Load("MyDAL");
            //反射获取类型
            Type[] type1 = MyDAL.GetTypes();
            //以接口形式保存被创建类的对象实例
            builder.RegisterTypes(type1)
                .AsImplementedInterfaces();

            //加载业务逻辑层这个程序集。  
            Assembly MyBLL = Assembly.Load("MyBLL");
            //获取dll中所有的类
            Type[] type2 = MyBLL.GetTypes(); 
            //以接口形式保存被创建类的对象实例
            builder.RegisterTypes(type2)
                .AsImplementedInterfaces();

        } 
    }
}

Autofac 的简单示例

注意:接口一定要有实现类,否则报错

构造函数注入

个人理解示意图,可能是错误的,如果错误还请指出,个人是小白一个


这里写图片描述


namespace MyBLL
{
    public class BaseServices
    {
        //创建接口对象,接口必须有实现类
        public IBaseDal dal;
        public BaseServices(IBaseDal _dal)
        {
            //由Autofac实现依赖注入,自动为接口创建对象(BaseDal类)
            dal = _dal;
        }
        public int GetSum(int num1,int num2)
        {
            int result = dal.GetSum(num1,num2);
            return result;
        }
    }
}
namespace MyIDAL
{
    public interface IBaseDal
    {
        int GetSum(int num1,int num2);
    }
}
namespace MyDAL
{
    public class BaseDal:IBaseDal
    {
        public int GetSum(int num1, int num2)
        {
            return num1 + num2;
        }
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值