WebApi中的Autofac

1.首先引用两个包

install-package autofac
install-package autofac.webapi2

2./App_Start/IocConfig.cs

在这个类里对依赖注入初始化

using Autofac;
using Autofac.Integration.WebApi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;

namespace WebApiAutoFac.App_Start
{
    public class IocConfig
    {
        public static void RegisterDependencies()
        {
            ContainerBuilder builder = new ContainerBuilder();
            HttpConfiguration config = GlobalConfiguration.Configuration;
            //获取正在执行的程序集
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //获取要注册的类的程序集
            Assembly[] assemblies = new Assembly[] { Assembly.Load("BLL") };
            //开始注册
            builder.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
    }
}

 3.Global 中调用上一步的初始化代码

//依赖注入
IocConfig.RegisterDependencies();

4.构造函数中自动注入

public class ProductController : ApiController
{
        private IProductInfoRepository _productInfoRepository;
 
        //在构造函数中自动注入
        public ProductController(IProductInfoRepository productInfoRepository) {
            _productInfoRepository = productInfoRepository;
        }
}

 

转载于:https://www.cnblogs.com/shx666/p/7898298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值