Mini 容器学习笔记10——方法注入
方法注入的条件:
1. 方法必须是实例方法
2. 方法必须有参数
3. 方法上必须贴有标签InjectAttribute
方法注入最佳原则
1. 当需要注入的方法的访问权限是私有时,应该把方法所属的类标记为密封类,具体原因请大家猜一猜。
2. 当类标记为密封类时,该类应该实现一个或多个契约接口(当如果需要对该类进行Aop拦截时,可以进行接口代理)
样例代码学习:
class Person4 : IPerson { public string Name { get; set; } public IHorse Horse { get; private set; } public bool HasVisited { get; private set; } public Person4() { } [Inject] void SetHorse(IHorse horse) { Horse = horse; HasVisited = true; } }
[Contract]
interface IHorse
{
}
class RedHorse : IHorse
{
}
[Test]
public void MethodInjectTest()
{
ServiceRegistry.Current
.Register(typeof(IPerson), typeof(Person4))
.Register(typeof(IHorse), typeof(RedHorse));
var instance = ServiceLocator.Get<IPerson,Person4>();
Assert.IsNotNull(instance);
Assert.IsNotNull(instance.Horse);
Assert.IsTrue(instance.HasVisited);
Assert.IsTrue(instance.Horse is RedHorse);
}
Mini 容器官方网站:
推荐资源:

浙公网安备 33010602011771号