ASP.NET Core中使用Unity5

2021-01-14 18:17

阅读:476

标签:set   技术   sys   gif   ade   resolve   gen   word   new   

原文:ASP.NET Core中使用Unity5

⒈添加相关依赖

Install-Package Unity
Install-Package Unity.RegistrationByConvention

⒉扫描项目接口实现类 

技术图片
 1 using System;
 2 using System.Linq;
 3 using Unity;
 4 using Unity.RegistrationByConvention;
 5 
 6 namespace Unity_Test.Unity
 7 {
 8     public class UnityConfig
 9     {
10         private static Lazy container = new Lazy(() =>
11         {
12             var container = new UnityContainer();
13             RegisterTypes(container);
14             return container;
15         });
16 
17         public static IUnityContainer GetConfiguredContainer()
18         {
19             return container.Value;
20         }
21 
22         public static void RegisterTypes(IUnityContainer container)
23         {
24 
25             var assemblyList = AllClasses.FromLoadedAssemblies().Where(w => w.FullName.Contains("Unity_Test"));
26 
27             container.RegisterTypes(
28                   assemblyList,
29                   WithMappings.FromAllInterfacesInSameAssembly,
30                   WithName.Default,
31                   WithLifetime.PerResolve);
32         }
33     }
34 }
技术图片

⒊代码中注入 

技术图片
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using Unity;
 5 
 6 namespace Unity_Test
 7 {
 8     public class Test
 9     {
10         [Dependency]
11         public IService service { get; set; }
12         public void sysout()
13         {
14             service.sayHello();
15             Console.ReadKey();
16         }
17     }
18 }
技术图片

 

技术图片技术图片技术图片

ASP.NET Core中使用Unity5

标签:set   技术   sys   gif   ade   resolve   gen   word   new   

原文地址:https://www.cnblogs.com/lonelyxmas/p/12940785.html


评论


亲,登录后才可以留言!