1

I'm building an API that needs to connect to a different database per request. Currently I'm using EF. These databases all have the same schema, therefore I can share a DbContext class. I have repositories to abstract persistence, and these are the ones using the DbContext objects.

Unity is handling dependency resolution, it is injecting my repositories with DbContext objects, and the repos on the controllers. Basically with zero configuration. I understand that probably I may need to create my own HttpRequestLifeCycle thing as suggested in this answer to make sure I have the same DbContext object through out the request.

Now, I would like to configure a ConnectionString to be used by Unity when creating DbContext objects to pass along to the repositories.

These ConnectionString will come from a repository (most likely a different fixed database), based on a parameter on my route. So, my intention is to have a delegating handler inspect the route, get the parameter, get the ConnectionString and tell Unity: "here, use this particular connection string when creating DbContext objects for my repositories during this request."

First, is my approach reasonable? Is this achievable? How would this dynamic parameter configuration done?

Thanks in advance,

Community
  • 1
  • 1
jhenriquez
  • 182
  • 9

1 Answers1

2

Yes, this is reasonable and achievable and frankly, easy.

Just approach this differently, instead of thinking how to inject connection strings, just register a factory for your db contexts. In the factory method, use the route information to read the connection string and return the context.

containe.Register<MyDbContext>( new InjectionFactory( 
  c => {
     // this is the factory method
     // the code will be executed upon each resolution

     String routeInfo = GetTenantFromCurrentRoute();

     String cs = GetCsFor( routeInfo );

     return new MyDbContext( cs );

  }, new PerHttpRequestLifetimeManager() )
Wiktor Zychla
  • 44,107
  • 6
  • 65
  • 91