Asp.net WebAPI 使用Autofac依赖注入

时间:2021-03-15 13:29:04

1、使用nupkg引用Autofac,Autofac.Mvc5和Autofac.Webapi2

PM> install-package autofac -version 3.5.0

PM> install-package autofac.mvc5

PM> install-package autofac.webapi2

(注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi,否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。”错误。这个坑自己中过,太不仔细)

 

2./App_Start/IocConfig.cs

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

public class IocConfig
{
public static void RegisterDependencies()
{
ContainerBuilder builder = new ContainerBuilder();
HttpConfiguration config = GlobalConfiguration.Configuration;
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t=>t.Name.EndsWith("Repository")).AsImplementedInterfaces();

//这种方式应该可以,但是没成功,还没找到原因
//var iRepository = Assembly.Load("Neighborly.IRepository");
//var repository = Assembly.Load("Neighborly.Repository");
//builder.RegisterAssemblyTypes(iRepository, repository).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();

//另外,如果是对单个接口和实现的注入,可以按一下方式。InstancePerApiRequest 似乎已经过时,InstancePerRequest 也可以
//builder.RegisterType<ProductInfoRepository>().As<IProductInfoRepository>().InstancePerRequest();

var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}

  

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

public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);

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

  

4.构造函数中自动注入

public class ProductController : ApiController
{
private IProductInfoRepository _productInfoRepository;

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