Reputation: 13
Interface:
public interface IPricingFactorsRepository
{
IList<LrfInputRates> GetLeaseRateFactorList(
string programCode,
string countryCode,
string currencyCode,
string leaseTerm);
}
Got below derived/implemented class:
public class PricingFactorsRepository : IPricingFactorsRepository
{
}
public class OverridePricingFactorsRepository : PricingFactorsRepository
{
}
Outside, there is such class that accept the interface as constructor parameter:
public class PricingHandler
{
public PricingHandler(IPricingFactorRepository pricingFactorRepository)
{
}
}
But with structuremap, it seems I can handle it with only one option:
x.For<IPricingFactorsRepository>().Use<PricingFactorsRepository>();
In some case, I would like the passed in parameter to be instances of PricingFactorsRepository
, some times, it should be OverridePricingFactorsRepository
.
Upvotes: 0
Views: 1204
Reputation: 29861
Using named instances you can create different objects based on the input:
ObjectFactory.Initialize(conf =>
{
conf.For<IPricingFactorsRepository>().Use<PricingFactorsRepository>();
conf.For<PricingHandler>().Use<PricingHandler>().Named("Default");
conf.For<PricingHandler>().Add<PricingHandler>().Named("Overriding")
.Ctor<IPricingFactorsRepository>().Is<OverridePricingFactorsRepository>();
});
Now you can get the different handler configurations by name. The default is the one with the PricingFactorsRepository
.
var ph = ObjectFactory.GetInstance<PricingHandler>();
var oph = ObjectFactory.GetNamedInstance<PricingHandler>("Overriding");
You'd want to combine this with a factory approach where the object depending on the pricing handler would get the different variants based on the user input.
public class PricingHandlerFactory
{
public PricingHandlerFactory(IContainer container)
{
_container = container;
}
public PricingHandler Create(string type)
{
var instance = ObjectFactory.TryGetInstance<PricingHandler>(type);
return instance ?? ObjectFactory.GetInstance<PricingHandler>();
}
}
Inject the PricingHandlerFactory where you need it (Structuremap will automatically wire it up, so there should be no need to configure it) and call the Create
method with the user input to get a PricingHandler
.
Upvotes: 2