views:

18

answers:

1

I would like to be able to inject named dependencies into a class using StructureMap if that is at all possible. The main reason I want this right now is for connection string injection.

I may be doing this the wrong way, but here's how I've got it (just need to add injection now):

psuedo:

public class MyServiceClass
     string connectionString;

     public MyServiceClass(string connectionString)
          this.connectionString = connectionString;

     public void DeleteObject
          var db = new EntitiesObject(connectionString)

Is there any way to put a name on the connection string constructor parameter so that StructureMap would know how to inject it?

EDIT: I could have multiple connection strings that are determined at run-time from a configuration database.

EDIT: One solution I've thought of is to create a ThisDatabaseConnectionString and a ThatDatabaseConnectionString class... that way it could inject the connection string based on type

A: 

You could do this (assuming that myConnectionString is a string instance):

container.Configure(r => r
    .ForConcreteType<MyServiceClass>()
    .Configure.Ctor<string>().Is(myConnectionString));

If you also need to map MyServiceClass from an interface (or abstract base class), you can do this instead:

container.Configure(r => r
    .For<IServiceClass>()
    .Use<MyServiceClass>()
    .Ctor<string>().Is(myConnectionString));

If you have previously configured named connection strings configured in the container, you can do something like this:

container.Configure(r => r
    .For<string>()
    .Use("foo")
    .Named("connStr1"));
container.Configure(r => r
    .For<string>()
    .Use("bar")
    .Named("connStr2"));
container.Configure(r => r
    .ForConcreteType<MyServiceClass>()
    .Configure.Ctor<string>().Is((IContext ctx) => 
        ctx.GetInstance<string>("connStr2")));
Mark Seemann
Could potentially need two different connection strings (not likely, but it happens)... I guess I'll probably go with my idea of creating a class for each connection string needed.
Max Schmeling
Couldn't you just select the appropriate connection string imperatively as part of your container setup?
Mark Seemann
BTW, see if my updated answer helps you...
Mark Seemann
I don't want the container setup to have to specify each place this connection string will be used. Unless I'm missing somethin.
Max Schmeling
It sounds like you want to make a convention-based setup of connection strings? If so, you may want to take a look at this: http://groups.google.com/group/structuremap-users/browse_thread/thread/6db0963489511d5c
Mark Seemann