安装包:Autofac.webapi2
注意:
install-package autofac.webapi2 (注意:您的项目中如果使用的是webapi2,此处必须为webapi2而不是webapi,否则在运行时将出现“重写成员“Autofac.Integration.WebApi.AutofacWebApiDependencyResolver.BeginScope()”时违反了继承安全性规则。重写方法的安全可访问性必须与所重写方法的安全可访问性匹配。”错误。)
在global 中 的Application_Start()添加
var builder = new ContainerBuilder();
//builder.RegisterControllers(Assembly.GetExecutingAssembly()); //Register MVC Controllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
//Register any other components required by your code....
builder.RegisterType<UserTest2>().As<IUserTest>();
var container = builder.Build();
// DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolver
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver
UserTest接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace webapiTest
{
public interface IUserTest
{
int GetI(int i);
}
public class UserTest : IUserTest
{
public int GetI(int i)
{
return i;
}
}
public class UserTest2 : IUserTest
{
public int GetI(int i)
{
return i*i;
}
}
}
使用:
public class DefaultController : ApiController
{
private IUserTest _userTest;
public DefaultController(IUserTest userTest)
{
_userTest = userTest;
}
// GET: api/Default/5
public int Get(int id)
{
return _userTest.GetI(id);
}
}
参考:
http://autofac.readthedocs.io/en/latest/integration/webapi.html#quick-start
https://weblogs.asp.net/shijuvarghese/dependency-injection-in-asp-net-web-api-using-autofac
https://stackoverflow.com/questions/26358287/how-do-i-resolve-web-api-controllers-using-autofac-in-a-mixed-web-api-and-mvc-ap
https://github.com/autofac/Examples
扩展:container 需要管理起来的
http://www.cnblogs.com/niuww/p/5649632.html