Based on the information provided, I would use the same controller and look at the connection string, rather than placing separate instances of the web API for each client. It would be more difficult to place multiple instances, and, given the only difference indicated in the connection string, I do not think the complexity will be justified.
The first thing we need to do is determine which client is being called in order to get the corresponding connection string. This can be done using tokens, headers, request data, or routing. Routing is the easiest and most affordable for clients, so I will demonstrate its use; however, carefully review your requirements when deciding how you will make the decision.
[Route( "{clientId}" )]
public Foo Get( string clientId ) { }
DbContext . DI, , , , , . factory, . Func<string, IUnitOfWork> , "clientId" IUnitOfWork. .
[RoutePrefix("foo")]
public class FooController : ApiController
{
private Func<string, IUnitOfWork> unitOfWorkFactory;
public FooController( Func<string, IUnitOfWork> unitOfWorkFactory )
{
this.unitOfWorkFactory = unitOfWorkFactory;
}
[Route( "{clientId}" )]
public Foo Get( string clientId )
{
var unitOfWork = unitOfWorkFactory(clientId);
}
}
, , , Func<string, IUnitOfWork>. . Autofac.
protected override void Load( ContainerBuilder builder )
{
builder.Register<MyDbContext>().ForType<DbContext>().InstancePerRequest();
builder.RegisterType<UnitOfWork>().ForType<IUnitOfWork>().InstancePerRequest();
builder.Register<Func<string, Bar>>(
c =>
{
var dbContextFactory = c.Resolve<Func<string, DbContext>>();
var unitOfWorkFactory = c.Resolve<Func<DbContext, IUnitOfWork>>();
return clientId =>
{
var connectionString = GetConnectionStringForClient(clientId);
return unitOfWorkFactory(dbContextFactory(connectionString));
};
});
}
Autofac , , Autofac , .
, .
:
builder.Register<Func<string, IEmployeeService>>(
c =>
{
var dbContextFactory = c.Resolve<Func<string, IMainContext>>();
var unitOfWorkFactory = c.Resolve<Func<IMainContext, IUnitOfWork>>();
var repositoryFactory = c.Resolve<Func<IMainContext, IEmployeeRepository>>();
var serviceFactory = c.Resolve<Func<IUnitOfWork, IEmployeeService>>();
return clientId =>
{
var connectionString = GetConnectionStringForClient(clientId);
IMainContext dbContext = dbContextFactory(connectionString);
IUnitOfWork unitOfWork = unitOfWorkFactory(dbContext);
IEmployeeRepository employeeRepository = repositoryFactory(dbContext);
unitOfWork.employeeRepositoty = employeeRepository;
return serviceFactory(unitOfWork);
};
});
, - , , , ( ) , , .