1
votes

I am using the LINQ to SQL Classes (DataContext) to connect to my DB. I have three databases with identical schema: Development, Staging and Live. I have realized that if they have an identical schema, I can connect to them using the same DataContext – by only changing the connection string that I pass in to the DataContext constructor. I have declared an interface so that all calls to the creation of the DataContext go through it:

public interface IDataContextCreator
    {
        MyDataContext CreateDataContext();
    }

Now I can have concerete implementations of this interface to connect to the Development, Staging or Live DBs.

I would now like to hide my DataContext constructor to force all calls to the creation of the DataContext go through the above interface. If I change the accessibility of the DataContext to internal, I cannot use it in other projects in the solution. I would ideally like to keep the class accessibility modifier as public but change the constructors to be internal. Is there any way to do this in the automatically generated classes? Is there any other solution to this problem?

Thank you.

Edit: Jon you are right the constructors should be made internal. I have these in my Data Layer, and I do not want classes in other projects/layers to get to these constructors. They however should be only able create the DataContext using the interface and then use the created DataContext - since it would be public on the class level.

2
Why would you want to change the constructors to protected rather than internal? - Jon Skeet
@WiktorZychla - I don't think these are duplicate because here I am concerned about the automatic generation of the DataContext. If I had to edit these by hand, I would simply keep the DataContext class as public (i.e. to be used by everyone) but keep the constructors internal. - O.O.

2 Answers

2
votes

You could replace the VS code gen with the T4 templates at http://l2st4.codeplex.com/. With this, you could then modify the constructor code spit to be protected rather than public.

However, I have to wonder why you are using separate data contexts rather than just changing the connection information in the config files and using a transform to pull the appropriate connection string for your particular build operation. See http://msdn.microsoft.com/en-us/library/dd465326.aspx

1
votes

You can declare your constructor as protected.

public class MyDataContext : DataContext {
    protected MyDataContext() {
    }
}