1

我是结构图的新手。我想根据用户输入获取具有“master”或“visa”依赖项的 Shopper 类对象。在下面的代码中,我从 ICreditCard 创建了两个具体类 MasterCard 和 Visa。我正在注入 ICreditCard 的依赖项,但是当基于用户的选项执行代码时,我想将 MasterCard 或 Visa 依赖注入 Shopper 类并获取该 Shopper 类对象的引用。

如果可能的话,有人可以告诉我该怎么做。我还想知道我是否想在其他类中初始化对象然后怎么做(是通过公开返回容器对象的方法吗?)

class Program
{
    static void Main(string[] args)
    {
        var container = new Container();
        container.Configure(c => c.For<ICreditCard>().Use<MasterCard>().Named("master"));
        container.Configure(x => x.For<ICreditCard>().Use<Visa>().Named("visa"));

        //how to get instance of Shopper with master card object reference?
        Console.ReadKey();
    }

    public class Visa : ICreditCard
    {
        public string Charge()
        {
            return "Visa... Visa";
        }

        public int ChargeCount
        {
            get { return 0; }
        }
    }

    public class MasterCard : ICreditCard
    {
        public string Charge()
        {
            ChargeCount++;
            return "Charging with the MasterCard!";
        }

        public int ChargeCount { get; set; }
    }

    public interface ICreditCard
    {
        string Charge();
        int ChargeCount { get; }
    }

    public class Shopper
    {
        private readonly ICreditCard creditCard;

        public Shopper(ICreditCard creditCard)
        {
            this.creditCard = creditCard;
        }

        public int ChargesForCurrentCard
        {
            get { return creditCard.ChargeCount; }
        }

        public void Charge()
        {
            Console.WriteLine(creditCard.Charge());
        }
    }
}
4

0 回答 0