Web API(六):使用Autofac实现依赖注入
在这一篇文章将会讲解如何在Web API2中使用Autofac实现依赖注入。
一、创建实体类库
1、创建单独实体类
创建DI.Entity类库,用来存放所有的实体类,新建用户实体类,其结构如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace DI.Entity 8 { 9 public class UserEntity 10 { 11 public int UserId { get; set; } 12 13 public string UserName { get; set; } 14 15 public int Sex { get; set; } 16 17 public int Age { get; set; } 18 } 19 }
二、创建仓储接口类库
新建DI.Interface类库文件,存放所有接口,IUserRepository接口定义如下:
using DI.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DI.Interface { public interface IUserRepository { List<UserEntity> GetUsers(); } }
三、创建仓储接口的实现类库
1、SQL Server数据库实现
新建DI.SqlServer类库文件,SqlServerUserRepository实现IUserRepository接口,SqlServerUserRepository类定义如下:
using DI.Entity; using DI.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DI.SqlServer { public class SqlServerUserRepository : IUserRepository { public List<UserEntity> GetUsers() { List<UserEntity> list = new List<UserEntity>() { new UserEntity(){UserId=1,UserName="王五",Sex=2,Age=21}, new UserEntity(){UserId=2,UserName="赵六",Sex=2,Age=23}, }; return list; } } }
2、Oracle数据库实现
新建DI.Oracle类库文件,OracleUserRepository实现IUserRepository接口,OracleUserRepository类定义如下:
using DI.Entity; using DI.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DI.Oracle { public class OracleUserRepository : IUserRepository { public List<UserEntity> GetUsers() { List<UserEntity> list = new List<UserEntity>() { new UserEntity(){UserId=1,UserName="张三",Sex=1,Age=24}, new UserEntity(){UserId=2,UserName="李四",Sex=1,Age=22}, }; return list; } } }
四、新建WebAPI项目
1、安装依赖项
通过NuGet安装所需的依赖项:Autofac、Autofac.WebApi2(如果使用的是WebApi1,这里需要安装WebApi)。
2、创建AutofacWebApiConfig类
AutofacWebApiConfig类定义如下:
using Autofac; using Autofac.Integration.WebApi; using DI.Interface; using DI.SqlServer; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; namespace WebApi.AutofacDI { public class AutofacWebApiConfig { public static void RegisterDependencies() { SetAutofacWebapi(); } private static void SetAutofacWebapi() { ContainerBuilder builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 使用SQLserver数据库实现 builder.RegisterType<SqlServerUserRepository>().As<IUserRepository>().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
3、修改Global.asax文件
修改后的Global.asax文件定义如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using WebApi.AutofacDI; namespace WebApi { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // 配置依赖注入 AutofacWebApiConfig.RegisterDependencies(); } } }
4、创建Users控制器
创建UsersController类,并在构造函数中注入,UsersController类定义如下:
using DI.Entity; using DI.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace WebApi.Controllers { public class UsersController : ApiController { private IUserRepository _userRepository; /// <summary> /// 构造函数中注入 /// </summary> /// <param name="userRepository"></param> public UsersController(IUserRepository userRepository) { this._userRepository = userRepository; } public IHttpActionResult Get() { return Json <List<UserEntity>>( _userRepository.GetUsers()); } } }
5、测试
启动程序,然后在浏览器里面输入:http://localhost:51157/api/users,结果如下:
从结果中可以看出:这里使用的是SQLserver实现的。
修改AutofacWebApiConfig文件,用oracle实现,修改后的代码如下:
using Autofac; using Autofac.Integration.WebApi; using DI.Interface; using DI.Oracle; using DI.SqlServer; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Http; namespace WebApi.AutofacDI { public class AutofacWebApiConfig { public static void RegisterDependencies() { SetAutofacWebapi(); } private static void SetAutofacWebapi() { ContainerBuilder builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 使用SQLserver数据库实现 //builder.RegisterType<SqlServerUserRepository>().As<IUserRepository>().InstancePerRequest(); // 使用oracle数据库实现 builder.RegisterType<OracleUserRepository>().As<IUserRepository>().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
运行结果:
从结果中可以看出:这里使用的是oracle实现的。
五、将Autofac的实现放到单独的类库中
新建DI.Server类库,将Autofac的注册单独放在类库中,AutofacWebApiConfig类定义如下:
using Autofac; using Autofac.Integration.WebApi; using DI.Interface; using DI.SqlServer; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web.Http; using System.Web.Mvc; namespace DI.Server { public class AutofacWebApiConfig { public static void RegisterDependencies() { SetAutofacWebapi(); } private static void SetAutofacWebapi() { ContainerBuilder builder = new ContainerBuilder(); HttpConfiguration config = GlobalConfiguration.Configuration; // Register API controllers using assembly scanning. builder.RegisterApiControllers(Assembly.LoadFrom(@"F:\Practice\WebAPI\WebApi依赖注入\DI\WebApiDIDemo\WebApi\bin\WebApi.dll")); builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces(); builder.RegisterType<SqlServerUserRepository>().As<IUserRepository>().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } } }
注意:
如果是在单独的类库项目中,注册Api控制器的时候要加载WebApi项目所有的程序集文件,不要使用builder.RegisterApiControllers(Assembly.GetExecutingAssembly()),这里找到的当前程序集是类库文件,不是WebApi项目的程序集文件,在控制器里面不会实现注入。
2、修改Global.asax文件
修改后的Global.asax文件定义如下:
using DI.Server; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebApi { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // 配置依赖注入(注意:这里使用的是单独类库里面的AutofacWebApiConfig类) AutofacWebApiConfig.RegisterDependencies(); } } }
运行程序,效果和上面的一样。