您好,登錄后才能下訂單哦!
這篇文章主要介紹了Web API中如何使用Autofac實現依賴注入的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Web API中如何使用Autofac實現依賴注入文章都會有所收獲,下面我們一起來看看吧。
創建DI.Entity類庫,用來存放所有的實體類,新建用戶實體類,其結構如下:
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.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(); } }
新建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; } } }
新建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; } } }
通過NuGet安裝所需的依賴項:Autofac、Autofac.WebApi2(如果使用的是WebApi1,這里需要安裝WebApi)。
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); } } }
修改后的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(); } } }
創建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()); } } }
啟動程序,然后在瀏覽器里面輸入: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實現的。
新建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項目的程序集文件,在控制器里面不會實現注入。
修改后的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實現依賴注入”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Web API中如何使用Autofac實現依賴注入”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。