How to pass parent/child class as constructor parameter with structuremap?

我与影子孤独终老i 提交于 2019-12-11 16:30:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18783889/how-to-pass-parent-child-class-as-constructor-parameter-with-structuremap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!