背景

使用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自动注入的更多相关文章

  1. Spring容器是如何实现 Bean 自动注入(xml)

    入口web.xml web.xml 配置文件 <!-- Spring Config --> <listener> <listener-class>org.sprin ...

  2. Servlet自动注入Spring容器中的Bean解决方法

    很多情况在进行Web开发的时候需要自己手写Servlet来完成某些功能,而servlet有需要注入Spring容器中的某些bean,这是每次都要手动获取比较麻烦,这里有一个解决方案,只需要写一个ser ...

  3. Istio技术与实践03:最佳实践之sidecar自动注入

    Istio通过对serviceMesh中的每个pod注入sidecar,来实现无侵入式的服务治理能力.其中,sidecar的注入是其能力实现的重要一环(本文主要介绍在kubernetes集群中的注入方 ...

  4. Asp.Net MVC 之 Autofac 初步使用2 集成mvc 属性注入以及自动注入

    首先看下Demo2的结构     然后下面一步步将Autofac集成到mvc中. 首先,定义Model Product.cs public class Product { public int Id ...

  5. .NET领域最为流行的IOC框架之一Autofac WebAPI2使用Autofac实现IOC属性注入完美解决方案 AutoFac容器初步

    .NET领域最为流行的IOC框架之一Autofac   一.前言 Autofac是.NET领域最为流行的IOC框架之一,微软的Orchad开源程序使用的就是Autofac,Nopcommerce开源程 ...

  6. 自己实现简单的AOP(五)使Demo适应webApi、亦可完成属性自动注入

    在前文的Demo中,webApi的Controller是不能自动注入的,原因是 IHttpController 和 IController 是通过两个不同的途径进行激活的. IHttpControll ...

  7. DotNetCore跨平台~autofac属性的自动注入

    回到目录 在使用autofac这个DI工具时,我们一般使用的是构造方法注入,而dotnetcore的标准框架里也集成了构造方法注入,而属性注入在一些场景下,表现的更为灵活,像java的spring框架 ...

  8. .NET MVC5+ EF+AutoFac自动注入框架

    1.创建一个MVC系统 VIEW显示页面代码: <link href="~/Content/bootstrap.css" rel="stylesheet" ...

  9. .NET MVC5+ Dapper+扩展+AutoFac自动注入实现

    1.首先创建一个MVC项目 定义Model 层  view 层 index.cshtml  控制器层Controllers等文件 2.在线安装或者引用dapper 以及扩展相关包 同时Autofac ...

随机推荐

  1. C++总结:C++中的const和constexpr

    C++中的const可用于修饰变量.函数,且在不同的地方有着不同的含义,现总结如下. const的语义 C++中的const的目的是通过编译器来保证对象的常量性,强制编译器将所有可能违背const对象 ...

  2. Java回顾之集合

    在这篇文章里,我们关注Java中的集合(Collection).集合是编程语言中基础的一部分,Java自JDK早期,就引入了Java Collection Framework.设计JCF的那个人,后来 ...

  3. angular-cli 文档

    Angular/angular-cli 原文来自:https://github.com/angular/angular-cli Angular/angular-cli 原文来自:https://git ...

  4. 由 '' in 'abc' return True 引发的思考----Python 成员测试操作

    最近遇到判断字典中是否存在空字符串‘’,这个很好判断,直接用:‘’ in ['a','b','c'],就可以直接判断出来:但是当我对字符串使用 “in” 方法进行判断的时候,发现:‘’ in ‘abc ...

  5. 校验基于EO的VO中的字段是否发生变化

    I have a table region and there are multiple records fetching from a Entity based VO. Now I have upd ...

  6. js 函数对象

    函数是进行模块化程序设计的基础,编写复杂的Ajax应用程序,必须对函数有更深入的了解: javaScript中的函数不同于其他的语言,每个函数都是作为一个对象被维护和运行的,通过函数对象的性质,可以很 ...

  7. oracle非空约束

    ALTER TABLE TB_ZJGL_DWSB_GRMX_LOG MODIFY HJQX   NULL;

  8. JSP Unable to compile class for JSP

    今天刚弄好MyEclipse环境,试了一下jsp的创建,然后就出现了一个很令人纠结的问题. 文档目录如下: Jsp代码如下: <%@page import="com.pd.Person ...

  9. PostgreSQL truncate table会释放索引的空间

    apple=# create table test(id integer, info text); CREATE TABLE apple=# insert into test select gener ...

  10. 第一个openGL程序

    一.工具的安装 因为要写C++程序,为了便捷,这里我安装的Visual Studio: 免费使用90天!安装好了之后,我们要为我们的开发安装相应的工具集: 因为我是要在windows上跑的,所以选择如 ...