WebApi中的Autofac
2021-04-26 09:26
标签:interface 依赖 ioc build ras imp 引用 sys new 1.首先引用两个包 2./App_Start/IocConfig.cs 在这个类里对依赖注入初始化 3.Global 中调用上一步的初始化代码 4.构造函数中自动注入 WebApi中的Autofac 标签:interface 依赖 ioc build ras imp 引用 sys new 原文地址:http://www.cnblogs.com/shx666/p/7898298.htmlinstall-package autofac
install-package autofac.webapi2
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);
}
}
}
//依赖注入
IocConfig.RegisterDependencies();
public class ProductController : ApiController
{
private IProductInfoRepository _productInfoRepository;
//在构造函数中自动注入
public ProductController(IProductInfoRepository productInfoRepository) {
_productInfoRepository = productInfoRepository;
}
}