运维开发网

利用WebAPI中的Autofac实现依赖注入

运维开发网 https://www.qedev.com 2022-07-17 21:02 出处:网络
本文详细讲解了WebAPI中使用Autofac实现依赖注入的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下 一、创建实体类库创建单独实体类

本文详细讲解了WebAPI中使用Autofac实现依赖注入的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下 一、创建实体类库创建单独实体类

创建DI。实体类库,用于存储所有实体类和创建新的用户实体类。其结构如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace DI.Entity{ public class UserEntity { public int UserId { get; set; } public string UserName { get; set; } public int Sex { get; set; } public int Age { get; set; } }}二、创建仓储接口类库

创建新的DI。用于存储所有接口的接口类库文件。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 { Listlt;UserEntitygt; 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 Listlt;UserEntitygt; GetUsers() { Listlt;UserEntitygt; list = new Listlt;UserEntitygt;() { 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 Listlt;UserEntitygt; GetUsers() { Listlt;UserEntitygt; list = new Listlt;UserEntitygt;() { 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 =gt; t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 使用SQLserver数据库实现 builder.RegisterTypelt;SqlServerUserRepositorygt;().Aslt;IUserRepositorygt;().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; /// lt;summarygt; /// 构造函数中注入 /// lt;/summarygt; /// lt;param name="userRepository"gt;lt;/paramgt; public UsersController(IUserRepository userRepository) { this._userRepository = userRepository; } public IHttpActionResult Get() { return Json lt;Listlt;UserEntitygt;gt;( _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 =gt; t.Name.EndsWith("Repository")).AsImplementedInterfaces(); // 使用SQLserver数据库实现 //builder.RegisterTypelt;SqlServerUserRepositorygt;().Aslt;IUserRepositorygt;().InstancePerRequest(); // 使用oracle数据库实现 builder.RegisterTypelt;OracleUserRepositorygt;().Aslt;IUserRepositorygt;().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } }}

运行结果:


从结果中可以看出,这里使用了oracle实现。

五、将Autofac的实现放到单独的类库中

创建新的DI。服务器类库,并把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 =gt; t.Name.EndsWith("Repository")).AsImplementedInterfaces(); builder.RegisterTypelt;SqlServerUserRepositorygt;().Aslt;IUserRepositorygt;().InstancePerRequest(); var container = builder.Build(); // Set the WebApi dependency resolver. config.DependencyResolver = new AutofacWebApiDependencyResolver(container); } }}

注意:

如果是在单独的类库项目中,注册Api控制器时要加载WebApi项目的所有汇编文件,不要使用builder.registerAPI控制器(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(); } }}

运行程序,效果同上。

关于在Web API中使用Autofac实现依赖注入的文章到此结束。希望对大家的学习有所帮助

0

精彩评论

暂无评论...
验证码 换一张
取 消