C# IOC容器 Autofac


原文:

 1.新建一個IService接口類

1  //定位Service程序集
2     public interface IService
3     {
4     }

  

  創建需要注入的服務類

  2.在新建一個用戶服務類

復制代碼
 1 using Entity;
 2     public interface IUserService
 3     {
 4         string AddUserInfo(Sys_User user);
 5 
 6         string GetUserPhone(string UserId);
 7     }
 8 
 9     public class UserService : IUserService
10     {
11         public string AddUserInfo(Sys_User user)
12         {
13             string newId = "1000000";
14             return string.Format("{0},注冊成功 ID為:{1}", user.Name, newId);
15         }
16 
17         public string GetUserPhone(string UserId)
18         {
19             return "18900000000";
20         }
21     }
復制代碼

 

  3.在新建一個信息處理服務類

復制代碼
 1 public interface IMessageService
 2     {
 3         void SendMessage(string Msg);
 4 
 5         string GetMessage(string UserID);
 6     }
 7 
 8     public class MessageService : IMessageService
 9     {
10         public string GetMessage(string UserID)
11         {
12             return "Hello World!";
13         }
14 
15         public void SendMessage(string Msg)
16         {
17             //發送成功
18         }
19     }
復制代碼

 

  4.在創建一個ServiceLocator類,用來獲取注入的服務

復制代碼
 1 using Autofac;//引包
 2     /// <summary>
 3     /// Autofac的服務定位器
 4     /// </summary>
 5     public class ServiceLocator
 6     {
 7         private static IContainer _container;
 8 
 9         /// <summary>
10         /// 設置Ico容器
11         /// </summary>
12         /// <param name="container"></param>
13         public static void SetContainer(IContainer container)
14         {
15             _container = container;
16         }
17 
18         /// <summary>
19         /// 獲取服務
20         /// </summary>
21         /// <typeparam name="IService"></typeparam>
22         /// <returns></returns>
23         public static IService GetService<IService>()
24         {
25             return _container.Resolve<IService>();
26         }
27 
28         /// <summary>
29         /// 獲取容器對象
30         /// </summary>
31         /// <returns></returns>
32         public static IContainer GetContainer()
33         {
34             return _container;
35         }
36     }
復制代碼

 

  5.在項目Global.asax中注冊服務類

復制代碼
 1 using Autofac;
 2     using Autofac.Integration.Mvc;
 3     using Service;
 4 
 5     public class MvcApplication : System.Web.HttpApplication
 6     {
 7         protected void Application_Start()
 8         {
 9             AreaRegistration.RegisterAllAreas();
10             RouteConfig.RegisterRoutes(RouteTable.Routes);
11 
12             //獲取Autofac容器構造器
13             var builder = new ContainerBuilder();
14             //注冊IService接口的程序集中包含Service的接口
15             builder.RegisterAssemblyTypes(typeof(Service.IService.IService).Assembly)
16                 .Where(t => t.Name.EndsWith("Service")) 
17                 .AsImplementedInterfaces();
18             //注冊項目的Controllers
19             builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly()).PropertiesAutowired();
20 
21             //獲取注入容器
22             var container = builder.Build();
23             //設置服務容器
24             ServiceLocator.SetContainer(container);
25             //設置MVC的注入解析程序
26             DependencyResolver.SetResolver(new AutofacDependencyResolver(ServiceLocator.GetContainer()));
27         }
28     }
復制代碼

 

  6.注入服務及調用

復制代碼
 1     using Entity;
 2     using Service;
 3     using Service.IService;
 4     public class HomeController : Controller
 5     {
 6         //兩種方式獲取注入的服務
 7 
 8         private readonly IUserService userService;
 9         //通過服務容器獲取
10         private readonly IMessageService messageService = ServiceLocator.GetService<IMessageService>();
11 
12         //通過構造函數注入
13         public HomeController(IUserService _userService)
14         {
15             this.userService = _userService;
16         }
17 
18         public ActionResult Index()
19         {
20             this.ViewBag.UserPhone = this.userService.GetUserPhone("張三");
21             this.ViewBag.Message = this.messageService.GetMessage("");
22             return View();
23         }
24     }
復制代碼

 

  7.測試結果

四.注冊注意事項。

  在Global.asax中注冊服務類的時候  我們為了防止注冊一些沒有必要的實體類進去。添加了一句條件

  加上這個注冊條件后 就表示你的所有需要注入的服務類 的類名都必須以Service結尾。否則就會導致在使用時報沒有注冊的錯誤。

  例如 下圖:把UserService 類名改為 UserTest

 

解決此問題,也可以這樣

注釋那句注冊時的篩選條件,但是值得注意的是,這樣就會造成資源浪費,把在同一個程序集下面的非服務類也給注冊進去了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM