views:

32

answers:

2

I am working on a asp.net MVC application.

The app is structured as follows:

  • Web MVC
  • Services - Business Rules
  • Data

The data layer is using LinqToSql to query the sql database.

When the user logs into the application, based on the username, I can do a lookup to check which organisation they fall under. Depending on the organisation, the database changes. That is, if user org is 1, it should use DB01 or if user org is 2 then DB02.

Both users have a common DB they use as well.

My question really is, how do I automate the selection of the target database. My thoughts are to do this from the Services layer. When initialising the Data class, I would pass in the connection string to the target DB.

However to do this, i will have to pass as a parameter to the Service layer the user token currently active, ie, org id/etc for the service to know this.

On the web project I am using the IModelBinder to bind the token is store it in the session.

Is there a nice way to pass the Imodelbinder object to the service layer or any other method I could use.

I want to move away from passing these values through method parameters.

A: 

requesting the database connect-string can also be a Service

Steven A. Lowe
+1  A: 

Since the question is tagged dependency-injection (DI) i assume that DI is already in use and the Data Access Component (DAC) is being injected into the Controllers.

As always with DI, the key to be able to vary injected dependencies by business logic is to introduce an Abstract Factory and inject that instead of the original component.

In your case, it may look somewhat like this:

public interface IRepositoryFactory
{
    IRepository Create(string userName);
}

The places where you previously injected your IRepository instances, you can now inject IRepositoryFactory and then use the userName to get the appropriate DAC.

Mark Seemann