Autofac容器使用属性进行WebApi自动注入
背景
使用Autofac进行依赖注入时,经常遇到的场景是在容器中进行类似如下代码的注入操作:
builder.RegisterType<BackInStockSubscriptionService>().As<IBackInStockSubscriptionService>().InstancePerLifetimeScope();
builder.RegisterType<CategoryService>().As<ICategoryService>().InstancePerLifetimeScope();
builder.RegisterType<CompareProductsService>().As<ICompareProductsService>().InstancePerLifetimeScope();
builder.RegisterType<RecentlyViewedProductsService>().As<IRecentlyViewedProductsService>().InstancePerLifetimeScope();
builder.RegisterType<ManufacturerService>().As<IManufacturerService>().InstancePerLifetimeScope();
builder.RegisterType<PriceFormatter>().As<IPriceFormatter>().InstancePerLifetimeScope();
builder.RegisterType<ProductAttributeFormatter>().As<IProductAttributeFormatter>().InstancePerLifetimeScope();
builder.RegisterType<ProductAttributeParser>().As<IProductAttributeParser>().InstancePerLifetimeScope();
因为这种注入是统一进行的,随着项目规模的扩大和代码复杂度的增加,需要在注册的地方不断地增加新的类来注册类型,这样会使代码失去了开闭原则:对修改关闭,对扩展开放。
解决方案
1. 定义一个属性用于标识类的注入意图,在应用初始化时利用反射进行集中类型注册。
public class InjectableAttribute : Attribute
{ }
2. 在需要注入的类型中,使用[Injectable]标记注入
public class Employee
{
public string Name { get; set; } public string Password { get; set; }
} public interface IEmployeeManager
{
IList<Employee> GetAllEmployess();
} public interface IEmployeeRepository
{
IList<Employee> GetAllEmployess();
} [Injectable]
public class EmployeeRepository : IEmployeeRepository
{
public IList<Employee> GetAllEmployess()
{
List<Employee> list = new List<Employee>();
list.Add(new Employee { Name = "a", Password = "b" });
return list;
}
} [Injectable]
public class EmployeeManager : IEmployeeManager
{
private readonly IEmployeeRepository _employeeRepository; public EmployeeManager(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
} public IList<Employee> GetAllEmployess()
{
var employeeData = _employeeRepository.GetAllEmployess();
var employeeList = new List<Employee>();
foreach (var employee in employeeData)
{
var employ = new Employee();
employ.Password= employee.Password;
employ.Name = employee.Name;
employeeList.Add(employ);
}
return employeeList;
}
}
3. 在WebApi的Controller中进行注入操作
public class EmployeeController : ApiController
{
private readonly IEmployeeManager _employeeManager; public EmployeeController(IEmployeeManager employeeManager)
{
_employeeManager = employeeManager;
} [AllowAnonymous]
[ResponseType(typeof(Employee))]
public IHttpActionResult GetEmployees()
{
var employeeData = _employeeManager.GetAllEmployess();
return Ok(employeeData);
}
}
4. 项目中引用 Autofac.WebApi2 and AutoFac,定义如下容器初始化类
public static class AutofacDependecyBuilder
{
public static void DependencyBuilder()
{
// Create the builder with which components/services are registered.
var builder = new ContainerBuilder(); // Register your Web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.GetCustomAttribute<InjectableAttribute>() != null)
.AsImplementedInterfaces()
.InstancePerRequest(); builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); //Build the Container
var container = builder.Build(); //Create the Dependency Resolver
AutofacWebApiDependencyResolver resolver = new AutofacWebApiDependencyResolver(container); //Configuring WebApi with Dependency Resolver
GlobalConfiguration.Configuration.DependencyResolver = resolver; } }
5. 在Web程序开始处调用容器注册
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes); AutofacDependecyBuilder.DependencyBuilder();
}
}
6.测试效果:
请求:

结果:

Autofac容器使用属性进行WebApi自动注入的更多相关文章
- Spring容器是如何实现 Bean 自动注入(xml)
入口web.xml web.xml 配置文件 <!-- Spring Config --> <listener> <listener-class>org.sprin ...
- Servlet自动注入Spring容器中的Bean解决方法
很多情况在进行Web开发的时候需要自己手写Servlet来完成某些功能,而servlet有需要注入Spring容器中的某些bean,这是每次都要手动获取比较麻烦,这里有一个解决方案,只需要写一个ser ...
- Istio技术与实践03:最佳实践之sidecar自动注入
Istio通过对serviceMesh中的每个pod注入sidecar,来实现无侵入式的服务治理能力.其中,sidecar的注入是其能力实现的重要一环(本文主要介绍在kubernetes集群中的注入方 ...
- Asp.Net MVC 之 Autofac 初步使用2 集成mvc 属性注入以及自动注入
首先看下Demo2的结构 然后下面一步步将Autofac集成到mvc中. 首先,定义Model Product.cs public class Product { public int Id ...
- .NET领域最为流行的IOC框架之一Autofac WebAPI2使用Autofac实现IOC属性注入完美解决方案 AutoFac容器初步
.NET领域最为流行的IOC框架之一Autofac 一.前言 Autofac是.NET领域最为流行的IOC框架之一,微软的Orchad开源程序使用的就是Autofac,Nopcommerce开源程 ...
- 自己实现简单的AOP(五)使Demo适应webApi、亦可完成属性自动注入
在前文的Demo中,webApi的Controller是不能自动注入的,原因是 IHttpController 和 IController 是通过两个不同的途径进行激活的. IHttpControll ...
- DotNetCore跨平台~autofac属性的自动注入
回到目录 在使用autofac这个DI工具时,我们一般使用的是构造方法注入,而dotnetcore的标准框架里也集成了构造方法注入,而属性注入在一些场景下,表现的更为灵活,像java的spring框架 ...
- .NET MVC5+ EF+AutoFac自动注入框架
1.创建一个MVC系统 VIEW显示页面代码: <link href="~/Content/bootstrap.css" rel="stylesheet" ...
- .NET MVC5+ Dapper+扩展+AutoFac自动注入实现
1.首先创建一个MVC项目 定义Model 层 view 层 index.cshtml 控制器层Controllers等文件 2.在线安装或者引用dapper 以及扩展相关包 同时Autofac ...
随机推荐
- javascript中new Date()会存在偏差一小时的bug
事件回顾: 因为我们的产品会有与时间转换这部分,并且流量主要集中在小程序. emmm~ 获取用户出生的年/月/日/时 我们和后台协商的是换算用户选择后的时间为 年/月/日/时/分/秒 所以我们 ...
- Linux修改字符集
set NLS_LANG=american_america.AL32UTF8-----Linux下查看及更改oracle字符集编码[root@OracleDB ~]# cd /usr/local/or ...
- win32程序应用mfc库
引入<afx.h> 此时会出现如下错误: #ifdef _DLL#ifndef _AFXDLL#error Building MFC application with /MD[d] (CR ...
- hdu 3682 10 杭州 现场 C - To Be an Dream Architect 简单容斥 难度:1
C - To Be an Dream Architect Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d &a ...
- sgu 146. The Runner 取模技巧 难度:1
146. The Runner time limit per test: 0.25 sec.memory limit per test: 4096 KB input: standard inputou ...
- SGU 144. Meeting 概率dp 几何概率分布 难度:0
144. Meeting time limit per test: 0.25 sec. memory limit per test: 4096 KB Two of the three members ...
- jquery+html5制作超酷的圆盘时钟表
自己封装的一个用HTML5+jQuery写的时钟表 代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...
- Chrome即将封杀Google Earth、Google Talk等插件
昨日,Chrome安全工程师Justin Schuh在官方博客中写道,到明年一月份,谷歌将封杀一系列基于NPAPI框架标准的浏览器插件.其中包括谷歌地球(Google Earth).Google Ta ...
- synchronized一个(二)
今天遇到了一个关于synchronized的一个问题,关于其持有锁的问题.这个问题以前是有看过相关文章的,但是一直没有记录,今天大概记录一下当前的认知. 对于静态方法,synchronized的使用的 ...
- jQuery插件开发——全屏切换插件
这个插件包含三个部分:HTML结构.CSS代码和JS代码. HTML结构是固定的,结构如下: <!--全屏滚动--> <div class="fullpage-contai ...