Tigraine

Daniel Hoelbling-Inzko talks about programming

How to make a LinQ2SQL DataContext IoC friendly

Posted by Daniel Hölbling on April 10, 2009

I’d really like to meet the guy who came up with the genius idea to call all parameters the same on the LinQ DataContext object:

image

So, when I tried to provide the connection through a named parameter with Castle Windsor I failed since the container can’t resolve what constructor to use (trying to match the key “connection”).

Thank god Microsoft didn’t seal the class so you can battle this problem by simply subclassing the construction:

public class InjectableDataContext : DataClassesDataContext
{
    public InjectableDataContext(string connectionString) 
        : base(connectionString)
    {
        
    }
}

Note that I directly subclassed my own LinQ2SQL DataContext (called DataClassesDataContext in this example).

Now I can have my configuration inject a connection string:

string myConnectionString = "DataSource...";
Component.For<DataClassesDataContext>()
    .ImplementedBy<InjectableDataContext>()
    .Parameters(Parameter.ForKey("connectionString").Eq(myConnectionString));

And the resolving code doesn’t change a bit:

var dbContext = container.Resolve<DataClassesDataContext>();

Filed under net, castle, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more