mare
mare

Reputation: 13083

IOC with MVC multiple registration for the same interface

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.

Upvotes: 2

Views: 297

Answers (2)

Dinesh
Dinesh

Reputation: 3770

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

Upvotes: 1

Val Bakhtin
Val Bakhtin

Reputation: 1464

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.

Upvotes: 0

Related Questions