views:

177

answers:

1

I want to inject a connection string into my repository but ideally, I want this connection string to be in my web.config connectionStrings section rather than in my windsor config. Is this possible?

I know I can use the fluent interface and achieve this easily but my bosses want an xml config file.

I also know that I can define a property and use that in my windsor config to pass the parameter in, but I have other code that reads the connectionstring from the web.config directly and do not really want two places with the same connectionString.

+1  A: 

There are several ways to do this:

  • This question has a solution that's very similar to what you want
  • You can tag the classes that need the connectionstring with an interface like this:

    interface IRequiresConnectionString {
        string ConnectionString {get;set;}
    }
    

    then you subscribe to the event container.Kernel.ComponentModelCreated (or write a IContributeComponentModelConstruction), inspect the component implementation type and if it implements IRequiresConnectionString you put the connectionString in the component's parameters.

  • You can also do the above without the interface if you follow the convention that the connectionstring parameter will always be called connectionString (or whatever you like) but this is error-prone, if you accidentally name your parameter conectionString it would not get injected.
Mauricio Scheffer
I would actually use `IContributeComponentModelConstruction` and convention to name the parameter 'connectionString' and write a unit test to verify I didn't screw that one up :)
Krzysztof Koźmic

related questions