62,074
社区成员
发帖
与我相关
我的任务
分享
UnityContainer container = new UnityContainer();//创建容器
container.RegisterType<ILocation, Door>("door");//注册依赖对象
container.RegisterType<ILocation, Sofa>("sofa");//注册依赖对象
//如何分别使用Door和Sofa的实例注入IAnimal?????????????????????
IAnimal animal = container.Resolve<Dog>(????);//返回调用者
animal.Call();//叫
/// <summary>
/// 动物
/// </summary>
public interface IAnimal
{
/// <summary>
/// 叫
/// </summary>
void Call();
}
/// <summary>
/// 狗
/// </summary>
public class Dog : IAnimal
{
[Dependency]
public ILocation Location { get; set; }
/// <summary>
/// 叫
/// </summary>
public void Call()
{
Console.WriteLine("狗在" + Location.GetName() + "汪汪汪……");
}
}
/// <summary>
/// 地点/场所
/// </summary>
public interface ILocation
{
string GetName();
}
/// <summary>
/// 大门
/// </summary>
public class Door : ILocation
{
public string GetName()
{
return "大门外";
}
}
/// <summary>
/// 沙发
/// </summary>
public class Sofa : ILocation
{
public string GetName()
{
return "沙发上";
}
}
UnityContainer container = new UnityContainer();
container.RegisterType<ILocation, Door>("Door");
container.RegisterType<ILocation, Sofa>("Sofa");
container.RegisterType<IAnimal, Dog>("Dog1", new InjectionConstructor(container.Resolve<ILocation>("Door")));
container.RegisterType<IAnimal, Dog>("Dog2", new InjectionConstructor(container.Resolve<ILocation>("Sofa")));
IAnimal animal1 = container.Resolve<IAnimal>("Dog1");
IAnimal animal2 = container.Resolve<IAnimal>("Dog2");
animal1.Call();
animal2.Call();
/// <summary>
/// 狗
/// </summary>
public class Dog : IAnimal
{
//[Dependency]
//public ILocation Location { get; set; }
private ILocation Location;
/// <summary>
/// 构造器
/// </summary>
/// <param name="location"></param>
public Dog(ILocation location)
{
this.Location = location;
}
//。。。。。
}
container.Resolve<Dog>("door")