ASP.NET Core中使用Unity5

⒈添加相关依赖

Install-Package Unity
Install-Package Unity.RegistrationByConvention

⒉扫描项目接口实现类 

 using System;
using System.Linq;
using Unity;
using Unity.RegistrationByConvention; namespace Unity_Test.Unity
{
public class UnityConfig
{
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
}); public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
} public static void RegisterTypes(IUnityContainer container)
{ var assemblyList = AllClasses.FromLoadedAssemblies().Where(w => w.FullName.Contains("Unity_Test")); container.RegisterTypes(
assemblyList,
WithMappings.FromAllInterfacesInSameAssembly,
WithName.Default,
WithLifetime.PerResolve);
}
}
}

⒊代码中注入 

 using System;
using System.Collections.Generic;
using System.Text;
using Unity; namespace Unity_Test
{
public class Test
{
[Dependency]
public IService service { get; set; }
public void sysout()
{
service.sayHello();
Console.ReadKey();
}
}
}

ASP.NET Core中使用Unity5ASP.NET Core中使用Unity5ASP.NET Core中使用Unity5

上一篇:阿里云数字巡展:“云上峰会”背后的秘密武器


下一篇:微信小程序开发和h5的区别