I am using StructureMap 4.4.1. In my code, I have 1 concrete class, TransactionalDatabaseClient
, that implements ITransactionalDatabaseClient
, which inherits from IDatabaseClient
. I'm using the Forward
method to redirect requests for ITransactionalDatabaseClient
to resolve using the registrations for the base interface, IDatabaseClient
.
Here is the relevant section of my Registry
:
For<IDatabaseClient>().Add(context => new TransactionalDatabaseClient(context.GetInstance<IConnectionManager>(), "sqlserver")).Named("sqlserver");
For<IDatabaseClient>().Add(context => new TransactionalDatabaseClient(context.GetInstance<IConnectionManager>(), "oracle")).Named("oracle");
Forward<IDatabaseClient, ITransactionalDatabaseClient>();
The problem is that when I request a named instance of ITransactionalDatabaseClient
, StructureMap complains that the named instance does not exist.
What am I doing wrong? Is there a workaround for this?
When you ask StructureMap for a named instance, it looks for an instance that was registered specifically for that interface, and doesn't check forwarding. The solution that worked for me was to just give up on forwarding and register the concrete twice, once for each interface.
For your problem that would look like this:
For<IDatabaseClient>().Add(context => new TransactionalDatabaseClient(context.GetInstance<IConnectionManager>(), "sqlserver")).Named("sqlserver");
For<IDatabaseClient>().Add(context => new TransactionalDatabaseClient(context.GetInstance<IConnectionManager>(), "oracle")).Named("oracle");
For<ITransactionalDatabaseClient>().Add(context => new TransactionalDatabaseClient(context.GetInstance<IConnectionManager>(), "sqlserver")).Named("sqlserver");
For<ITransactionalDatabaseClient>().Add(context => new TransactionalDatabaseClient(context.GetInstance<IConnectionManager>(), "oracle")).Named("oracle");