1

We are currently using StructureMap as the IoC container. All was working ok, but now we need to change the defaults in runtime.

What we need is ability to provide IEntityRepository, IEntityService based on a user. Having EntityRepositoryEur, EntityRepositoryRus...

Is there some way how to chnage Instances in runtime based on user setting? What is the best way to do that? Maybe is there some better IoC right now to do that?

1 Answer 1

1

I am not familiar with StructureMap but with Unity Application Block (called usually just Unity) you can register more concrete types (services) with single interface. You assign names to these services and at the time of resolution you receive the list of registered services. Then you can choose one based on the user settings.

This is example how to register named services using config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <unity>
    <containers>
      <container>
        <types>
          <type name="OutputService1" type="InterfacesLibrary.IOutputService, InterfacesLibrary" mapTo="InputOutputLibrary.ConsoleOutputService, InputOutputLibrary" />
          <type name="OutputService2" type="InterfacesLibrary.IOutputService, InterfacesLibrary" mapTo="InputOutputLibrary.MsgBoxOutputService, InputOutputLibrary" />
        </types>
      </container>
   </containers>
  </unity>
</configuration>

Or you can do the same thing from code

container.RegisterType<IOutputService, ConsoleOutputService>("OutputService1");
container.RegisterType<IOutputService, MsgBoxOutputService>("OutputService2");

At the time of resolution you resolve one or the other type based on user's requirements

    IOutputService outputService;
    if (user.LikesConsole == true)
      outputService = container.Resolve<IOutputService>("OutputService1");
    else
      outputService = container.Resolve<IOutputService>("OutputService2");

Have a look at the series of videos on PRISM. The second video is introduction to Unity.

Sign up to request clarification or add additional context in comments.

2 Comments

Please, give a clue, small example. If I wil understand your suggestion, I will learn more about it
I added the example to my answer above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.