asp.netasp.net-mvcdependency-injectioninversion-of-controlstructuremap

IOC with multiple databases that use same interface (StructureMap or any other DI Framework)


We've been experimenting with StructureMap, and I'm having trouble grasping how to handle situations where a single interface has multiple implementations. The code below shows an example where we have two databases that are both accessible from a single service.

public class SomeController : Controller
{
    private ISomeService _service;
    private IClientRepository _repository;
    protected IContext _masterContext;
    protected IContext _clientContext;

    public SomeController(ISomeService service, ISomeRepository repository
        , IContext masterCon, IContext clientCon)
    {
        _service = service;
        _repository = repository;
        _masterContext = masterCon;
        _clientContext = clientCon;
    }
}

public class SomeService : ISomeService
{
    private IContext _masterContext;
    private IContext _clientContext;

    public SomeService(IContext masterContext, IContext clientContext)
    {
        masterContext = _masterContext;
        clientContext = _clientContext;
    }
}

public class ClientRepository : IClientRepository
{
    private IContext _clientContext;

    public ClientRepository(IContext clientContext)
    {
        _clientContext = clientContext;
    }
}

public class MasterContext : IContext
{
    public MasterContext(String connString)
    //<snip, snip> implement 3rd party data context
}

public class ClientContext : IContext
{
    public ClientContext(String connString)
    //<snip, snip> implement 3rd party data context
}

StructureMap worked GREAT when we had a single context (database), but how do I tell it how to resolve the 2nd? Note: in most situations we wouldn't have a service handling 2 databases (but may have a controller handling 2 connections, i.e. 2 repositories accessing 2 different databases), but it still doesn't seem to make it easier.

I'm half ready to just give up on using an IoC framework and go back to poor man's DI.


Solution

  • Is it not possible to have an IClientContext and an IMasterContext, possibly inheriting from IContext. My feeling is that the code would be doing one of two very different things depending on whether you were talking to the 'Master' or 'Client' database.