Autofac in webapi2

 

安装包: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

转载于:https://www.cnblogs.com/kingreatwill/p/7070203.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值