StructureMap Autowiring with two different instances of the same interface

Posted by Lambda on Stack Overflow See other posts from Stack Overflow or by Lambda
Published on 2011-01-09T01:47:33Z Indexed on 2011/01/09 1:54 UTC
Read the original article Hit count: 493

Filed under:
|
|

For the last two days, i tried my best to learn something about StructureMap, using an old project of mine as an concrete implementation example. I tried to simplify my question as much as possible. While i will post my examples in vb.net, answers with examples in C# are also okay.

The project includes an interfaces called IDatabase which connects itself to a Database. The important part looks like this.

Public Interface IDatabase
    Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean
    ReadOnly Property ConnectionOpen As Boolean
    [... more functions...]
End Interface

Public Class MSSQLConnection
    Implements IDatabase
    Public Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean Implements IDatabase.Connect

       [... Implementation ...]

    End Function

[... more implementations...]
End Class

ConnectionSettings is a structure that has all the information needed to connect to a Database.

I want to open the Database Connection once and use it for every single connection in the project, so i register a instance in the ObjectFactory.

dim foo = ObjectFactory.GetInstance(Of MSSQLConnection)()
dim bar as ConnectionSettings
foo.connect(bar)
ObjectFactory.Configure(Sub(x) x.For(Of IDatabase).Use(foo))

Up until this part, everything works like a charm. Now, i get to a point where i hav e classes that need an additional instance of IDatabase because they connect to a second database.

Public Class ExampleClass
Public Sub New(ByVal SameOldDatabase as IDatabase, ByVal NewDatabase as IDatabase)
[...] Magic happens here [...]
End Sub
End Class

I want this second IDatabase to behave much like the first one. I want it to use a concrete, single instance and want to connect it to a different database invoking Connect with a different ConnectionSettings.

The problem is: While i'm pretty sure it's somewhow possible, (my initial idea was registering ExampleClass with alternative constructor arguments), i actually want to do it without registering ExampleClass. This probably involves more configuration, but i have no idea how to do it.

So, basically, it comes down to this question: How do i configurate the ObjectFactory in a way that the autowiring always invokes the constructor with object Database1 for the first IDatabase parameter and object Database2 for the second one (if there is one?)

© Stack Overflow or respective owner

Related posts about c#

Related posts about vb.net