⒈添加相关依赖
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();
}
}
}