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<IUnityContainer> container = new Lazy<IUnityContainer>(() => 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 }