Unity (IoC) with Strategy Pattern, replacing Switch statements


Any tips how to use a IoC container (unity) when applying Strategy Pattern for replacing  Switch Statements

Applying Strategy Pattern Instead of Using Switch Statements

Implementing a Strategy Pattern using the Unity Framework
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can't use Ioc for a strategy as far i see.  Since you have to deceide which class you want to instantiate based on some value. Use factory partern instead, a simple way.

It is not as straight as it looks like for repository pattern.
ulf-jzlAuthor Commented:
I solved it, don't know if there is a better way, but it works fine .

         var dataExporters = new object[]  
            var dataExporterTypes = new object[]  

            var ic= new InjectionConstructor(
                new ResolvedParameter<IExporter>("CsvExporter"),
                new ResolvedArrayParameter<DataExporterType>(dataExporterTypes),
                new ResolvedArrayParameter<IDataExporter>(dataExporters));

            container.RegisterType<IExporterFactory, ExporterFactory>("ExporterFactory", (ic));

public class ExporterFactory : IExporterFactory
    private readonly Dictionary<DataExporterType, IDataExporter> strategies =
        new Dictionary<DataExporterType, IDataExporter>();

    private readonly IExporter exporter;

    public ExporterFactory(
        IExporter exporter,
        DataExporterType[] measurementType,
        IDataExporter[] dataExporters)
        this.exporter = exporter;

        for (int i = 0; i < measurementType.Length; i++)
            strategies.Add(measurementType[i], dataExporters[i]);

    public IExporter CreateExporter(DataExporterType measurementType)
        return this.exporter.Create(strategies[measurementType]);

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ulf-jzlAuthor Commented:
Solved it
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.