views:

243

answers:

1

Hi,

I am currently setting the connection string for my linq to sql data context by using a wrapper class so that I can pass a connection string into the generated DataContext constructor:

    public class DB : GeneratedDataContext {
    public DB() : base(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString) { }
}

My LinqToSql repository implementations then work with the DB class directly.

I am using StructureMap and wonder whether this is the best approach for this i.e. should I instead, take a connection string parameter as a constructor on my repository and set this argument within my StructureMap boot strapper?

Thanks, Ben

+2  A: 

Short answer to your question: yes, structuremap should handle the config of your db connection.

I use something like this to register my datacontext with structuremap

ForRequestedType<MyDataContext>()
    .CacheBy(StructureMap.Attributes.InstanceScope.Hybrid)
    .TheDefault.Is.ConstructedBy(
         () => 
         new MyDataContext(ConfigurationManager
                               .ConnectionStrings["MyConnectionString"]
                               .ConnectionString)
         );

That way, you won't need a wrapper for your datacontext either.

Kirschstein
Great, thanks. My repositories currently call a parameterless constructor on my data context wrapper. So if I implement your suggestion how do I instantiate new instances of the data context within my repositories (as they expect a connection string to be passed into the constructor)? Thanks
Ben
@Ben Your repositories shouldn't be creating new instances of your datacontext, they should be being injected by structuremap
Kirschstein
Okay I understand. So this is like the example at http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx. One question then, I am using an atomic approach for my update methods (instantiating a new data context and wrapping in a using statement so properly disposed). Should I continue to do this?
Ben
@Ben datacontext is lightweight enough to make that a reasonable approach (do you mean more like a unit of work pattern?). If you're doing that, you may want to consider injecting a DataContextFactory into your repositories. Ideally, you want to avoid a `new` in your repository code, and you also dont want to have to couple it to StructureMap directly by having an ObjectFactory call in there either.
Kirschstein
@Kirschstein - thanks for this. I'm happy with injecting the data context in for my read methods but yes would like to use the unit of work approach with any writes so will looking into using a factory for this. Thanks for all your help.
Ben