Unity的函数依赖注入和之前提到的构造函数、属性使用相同。InjectionMethodAttribute指定需要注入的函数。
1 public static class AppDomainUnity 2 { 3 public static readonly IUnityContainer Instance = new UnityContainer(); 4 } 5 6 public sealed class MyObject 7 { 8 public MyObject() { } 9 10 [InjectionMethod] 11 public void Initialize(IMyInterface myInterface, IMyInterface2 myInterface2) 12 { 13 14 } 15 } 16 17 IUnityContainer unityContainer = AppDomainUnity.Instance; 18 19 unityContainer.RegisterType<IMyInterface, MyInterfaceImpl>(); 20 unityContainer.RegisterType<IMyInterface2, MyInterface2Impl>(); 21 22 MyObject myObject = unityContainer.Resolve<MyObject>();
DependencyAttribute可以指定需要依赖注入的注册名称。OptionalDependencyAttribute在没有注册相应类型的时候默认返回null。