2

How does one register multiple data providers for certain interface with IOC (I use Ninject but you can answer in general), for instance ISettingsRepository is implemented by JsonSettingsProvider and XmlSettingsProvider.

I am migrating my data (settings in this case) from XML to JSON and need to use both of them at the same time in application (not chosing between one of them but both at the same time at runtime). So I need XML based provider to read in what was serialized and use JSON provider to serialize it back as JSON.

public class WebSettings
{
    [Inject] 
    private ISettingsRepository _repository;

    private void Load()
    {
        _repository = DependencyResolver.Current
            .GetService<ISettingsRepository>();

        ...

Now I'd have registration such as:

kernel.Bind<ISettingsRepository>()
    .To<XmlSettingsProvider>()
    .InRequestScope();

Hopefully you understand what I mean.

Steven
  • 166,672
  • 24
  • 332
  • 435
mare
  • 13,033
  • 24
  • 102
  • 191
  • Just a thought, is it not possible you can use the Factory pattern to choose the correct implementation of class (either JsonSettingsProvider or XMLSettingsProvider) and return the ISettingsRepository interface as returntype in factory method under the condition as per your requirement... what do you think??? – Dinesh May 12 '12 at 14:35
  • yes that is one option, have not used Factories so far, so a code sample would be nice – mare May 12 '12 at 14:43

2 Answers2

1

I tried but could not manage to do so using Factory.

But you may have a look at this thread on stackoverflow

Ninject : Resolving an object by type _and_ registration name/identifier

Community
  • 1
  • 1
Dinesh
  • 3,652
  • 2
  • 25
  • 35
0

I know unity (link on msdn) supports several named instances of the same type:

public IUnityContainer RegisterInstance(
    Type t,
    string name,
    Object instance,
    LifetimeManager lifetime
)

and then when you resolve, just pass the name of required instance.

Val Bakhtin
  • 1,434
  • 9
  • 11