Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Autofac to implement dependency injection in Web API

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the Web API how to use Autofac to achieve dependency injection related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this Web API article on how to use Autofac to achieve dependency injection, let's take a look.

First, create an entity class library to create a separate entity class

Create a DI.Entity class library, which is used to store all entity classes and create new user entity classes. The structure is as follows:

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;}} II. Create warehousing interface class library

Create a new DI.Interface class library file to store all the APIs. The IUserRepository API is defined as follows:

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 GetUsers ();}} III. Create the implementation class library of the warehousing interface 1. SQL Server database implementation

Create a new DI.SqlServer class library file, and SqlServerUserRepository implements the IUserRepository API. The SqlServerUserRepository class is defined as follows:

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 GetUsers () {List list = new List () {new UserEntity () {UserId=1,UserName= "Wang Wu", Sex=2,Age=21}, new UserEntity () {UserId=2,UserName= "Zhao Liu", Sex=2,Age=23},}; return list }} 2. Oracle database implementation

Create a new DI.Oracle class library file, and OracleUserRepository implements the IUserRepository API. The OracleUserRepository class is defined as follows:

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 GetUsers () {List list = new List () {new UserEntity () {UserId=1,UserName= "Zhang San", Sex=1,Age=24}, new UserEntity () {UserId=2,UserName= "Li Si", Sex=1,Age=22},}; return list Fourth, create a new WebAPI project 1 and install dependencies

Install the required dependencies through NuGet: Autofac, Autofac.WebApi2 (if you are using WebApi1, you need to install WebApi here).

2. Create the AutofacWebApiConfig class

The AutofacWebApiConfig class is defined as follows:

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 (); / / use SQLserver database to implement builder.RegisterType (). As (). InstancePerRequest (); var container = builder.Build (); / / Set the WebApi dependency resolver. Config.DependencyResolver = new AutofacWebApiDependencyResolver (container);} 3. Modify Global.asax file

The modified Global.asax file is defined as follows:

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); / / configure dependency injection AutofacWebApiConfig.RegisterDependencies ();} 4, create Users controller

Create the UsersController class and inject it into the constructor. The UsersController class is defined as follows:

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 / public UsersController (IUserRepository userRepository) {this._userRepository = userRepository;} public IHttpActionResult Get () {return Json (_ userRepository.GetUsers ();} 5, test

Start the program, then type: http://localhost:51157/api/users in the browser, and the result is as follows:

You can see from the result that what is used here is implemented by SQLserver.

Modify the AutofacWebApiConfig file and implement it with oracle. The modified code is as follows:

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 (); / / using SQLserver database to implement / / builder.RegisterType (). As (). InstancePerRequest (); / / using oracle database to implement builder.RegisterType (). As (). InstancePerRequest () Var container = builder.Build (); / / Set the WebApi dependency resolver. Config.DependencyResolver = new AutofacWebApiDependencyResolver (container);}

Running result:

You can see from the result that what is used here is implemented by oracle.

Fifth, put the implementation of Autofac into a separate class library

Create a new DI.Server class library, and put the registration of Autofac in the class library separately. The AutofacWebApiConfig class is defined as follows:

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 dependency injection\ DI\ WebApiDIDemo\ WebApi\ bin\ WebApi.dll"); builder.RegisterAssemblyTypes (AppDomain.CurrentDomain.GetAssemblies ()) .Where (t = > t.Name.EndsWith ("Repository")). AsImplementedInterfaces (); builder.RegisterType (). As (). InstancePerRequest (); var container = builder.Build (); / / Set the WebApi dependency resolver. Config.DependencyResolver = new AutofacWebApiDependencyResolver (container);}

Note:

If you are in a separate class library project, when you register the Api controller, you need to load all the assembly files of the WebApi project. Do not use builder.RegisterApiControllers (Assembly.GetExecutingAssembly ()). The current assembly found here is the class library file, not the assembly file of the WebApi project. Injection will not be implemented in the controller.

2. Modify Global.asax file

The modified Global.asax file is defined as follows:

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); / / configure dependency injection (Note: the AutofacWebApiConfig class in the separate class library is used here) AutofacWebApiConfig.RegisterDependencies ();}

Run the program, the effect is the same as the above.

This is the end of the article on "how to use Autofac to implement dependency injection in Web API". Thank you for reading! I believe you all have a certain understanding of "how to use Autofac to achieve dependency injection in Web API". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report