Asp.Net Mvc使用Autofac实现依赖注入(实战)
前言
上一篇博客看似会了,实战又会遇到各种问题,实战很重要
Api层添加依赖
可通过NugetPackage管理搜索安装如下依赖
Autofac.WebApi2
Autofac
Api层App_Start文件夹下新建AutofacConfig.cs
public class AutofacConfig
{
public static void Register()
{
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
//注入Service
builder.RegisterAssemblyTypes(Assembly.Load("CodeFirst.Frame.Service")).AsImplementedInterfaces().InstancePerDependency();
//注入Log
//builder.Register<ILogger>((c, p) =>
//{
// return new LoggerConfiguration().ReadFrom.AppSettings().CreateLogger();
//}).SingleInstance();
builder.RegisterWebApiFilterProvider(config);
var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
接口
namespace CodeFirst.Frame.Service
{
public interface ISMSService
{
List<SMS> GetSMS();
}
}
实现
namespace CodeFirst.Frame.Service
{
public class SMSService :ISMSService
{
public List<SMS> GetSMS()
{
using (var db = new ServiceDbContext())
{
var query = from s in db.SMS
select s;
var resultSMS = query.ToList();
return resultSMS;
}
}
}
}
Api层构造注入
public class ValuesController : ApiController
{
private readonly ISMSService _sMSService;
//构造注入
public ValuesController(ISMSService sMSService)
{
this._sMSService = sMSService;
}
[HttpGet]
[Route("Values/Values")]
public List<CodeFirst.Frame.Service.SMS> GetSMS()
{
var result = _sMSService.GetSMS();
return result;
}
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody] string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
注入注册
别忘记在Global.asax里注册一下注入服务
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//注册注入
AutofacConfig.Register();
}
常见问题
“ExceptionMessage”: “An error occurred when trying to create a controller of type ‘ValuesController’. Make sure that the controller has a parameterless public constructor.”,
解决方案
如果你按照我的步骤操作不会遇到这个问题,问题在于构造注入的时候,必须注入接口而非实现,注入实现会遇到此报错
不注册服务也会遇到此错误。
仅供学习参考,如有侵权联系我删除