I am new to structuremap. I want to get Shopper classes object with either "master" or "visa" dependency based on user input. In below code I have created two concrete classes MasterCard and Visa from ICreditCard. I am injecting dependency of ICreditCard but when code is executing based on user's option I want to inject MasterCard or Visa depdency to Shopper class and get reference of that Shopper class object.
Can someone tell me how to do it if it is possible. I also want to know if I want to initialise object in some other class then how to do it(is it by exposing a method returning container object?)
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());
}
}
}