Asp.Net MVC 之 Autofac 初步使用3 集成web api

时间:2022-03-17 07:20:08

今天我们试着在WebApi2实现autofac的注入,关于这方面也是看了几位园友的分享省了不少时间,,所以结合着前篇的demo再新建webapi进行...

demo3下载地址:  

一样开篇还是发下大概demo结构:

还是nuget安装 Autofac 以及 Autofac ASP.NET MVC 5  Integration 、Autofac ASP.NET WEB API 2.2 Integration

看到有园友说属性注入存在安全隐患,官方的建议是使用构造函数注入。

特意找了一下相关的内容,不过不确定观点是否正确,有明白的朋友麻烦可以告知下,我也好补充下让更多朋友明白哈,在此感谢。

优缺点:

1. 属性注入直白易懂,缺点是对于属性可选的时候,很多个构造函数会显得类很臃肿。

2. 构造注入是一种高内聚的体现,特别是针对有些属性需要在对象在创建时候赋值,且后续不允许修改(不提供setter方法)。

不啰嗦了,主要还是贴下WebApi2的Global文件,里面主要关注关于mvc与webapi注册的地儿(红色部分)

#region 自动注入 //创建autofac管理注册类的容器实例 var builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray(); //注册所有实现了 IDependency 接口的类型 Type baseType = typeof(IDependency); builder.RegisterAssemblyTypes(assemblies) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsSelf().AsImplementedInterfaces() .PropertiesAutowired().InstancePerLifetimeScope(); //注册MVC类型 // builder.RegisterControllers(assemblies).PropertiesAutowired(); //注册Api类型 builder.RegisterApiControllers(assemblies).PropertiesAutowired(); //builder.RegisterFilterProvider(); builder.RegisterWebApiFilterProvider(config); var container = builder.Build(); //注册api容器需要使用HttpConfiguration对象 config.DependencyResolver = new AutofacWebApiDependencyResolver(container); //注册解析 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion

新添加 TestController

[RoutePrefix("api/Test")] public class TestController : ApiController { readonly IUserRepository repository; //构造器注入 public TestController(IUserRepository repository) { this.repository = repository; } [HttpGet] public HttpResponseMessage Index() { return MessageToJson.ToJson(repository.GetAll()); } }

MessageToJson 只是把结果转了一下json

//需添加 System.Web.Extensions.dll 引用 public static HttpResponseMessage ToJson(Object obj) { String str; if (obj is String || obj is Char) { str = obj.ToString(); } else { var serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; }

最后来测试下结果:

访问/api/Test/Index

Asp.Net MVC 之 Autofac 初步使用3 集成web api