解析从Unity Container实现多个接口的实例

时间:2016-06-22 10:24:21

标签: c# .net unity-container

请参阅我目前的代码

public interface ICoach
    {
        void Test();
    }

    public class Player : IPlayer
    {
        void IPlayer.Run()
        {
            Console.WriteLine(this.Name + "Run");
        }

        void IPlayer.Jump()
        {
            Console.WriteLine(this.Name + ": Jump");
        }

        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }


        public Player(string name)
        {
            Name = name;
        }
    }

    public class Coach : ICoach
    {
        void ICoach.Test()
        {
            Console.WriteLine("Test");
        }
    }

    public class SuperPlayer : ICoach, IPlayer
    {
        private int count = 0;

        public void Test()
        {
            Console.WriteLine("Super player test");
            count++;
        }

        public void Run()
        {
            Console.WriteLine("Super player run");
            count++;
        }

        public void Jump()
        {
            Console.WriteLine("Super player jump");
            count++;
        }

        public void PrintRunTimes()
        {
            Console.WriteLine(string.Format("Super player runs {0} times", count));
        }
    }

container.RegisterType<IPlayer, Player>();
container.RegisterType<ICoach, Coach>();
container.RegisterType<ICoach, SuperPlayer>("super", new ContainerControlledLifetimeManager());
container.RegisterType<IPlayer, SuperPlayer>("super", new ContainerControlledLifetimeManager());

SuperPlayer类实现两个接口:IPlayer和ICoach; Player类实现IPlayer接口,Coach类实现ICoach interafce。

我可以使用super参数解析SuperPlayer实例。但它是单身人士。如果我不这样注册,使用super参数从IPlayer和ICoach解析将返回2个差异实例。有没有办法解析SuperPlayer实例,而不是单例实例?

1 个答案:

答案 0 :(得分:0)

您可以创建一个新的ISuperPlayer界面,其中包含ICoach&amp; IPlayer。然后根据需要实现,注册和解析该接口。