注:这个问题确实有点类似于this one https://stackoverflow.com/questions/21388655/can-i-programmatically-determine-the-database-context-to-use-based-on-user-cre,但我想我可以用更简单、更具体的方式来表达。
我使用 Castle Windsor 拦截传递给我的 Web API 应用程序的 URI,以将适当的具体类注册到控制器的构造函数。
我想要做的是在 URI 上传递一个“站点编号”,也许始终作为第一个或最后一个参数。 IOW,对于站点 42,而不是
http://localhost:28642/api/platypi/GetAll
...这将是:
http://localhost:28642/api/platypi/42/GetAll
-or:
http://localhost:28642/api/platypi/GetAll/42
当我的 Web API 应用程序第一次“看到”/拦截 URI 时,我想记下该站点编号,以便我可以分配所需的具体存储库以由温莎城堡注册。我希望能够做到这一点:
public class RepositoriesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
if (siteNum == 42)
{
container.Register(
Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository42>().LifestylePerWebRequest(),
Component.For<IInventoryItemRepository>().ImplementedBy<InventoryItemRepository42>().LifestylePerWebRequest(),
. . .
}
else if (siteNum = 77)
{
container.Register(
Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository77>().LifestylePerWebRequest(),
Component.For<IInventoryItemRepository>().ImplementedBy<InventoryItemRepository77>().LifestylePerWebRequest(),
. . .
}
通过这种方式,我可以为站点 42 提供其数据,为站点 77 提供其数据(每个站点使用共享公共架构的不同数据库)。
那么:在我的 Web API 应用程序生命周期中的哪个时刻,我可以劫持 URI,以便将适当的 val 分配给全局 siteNum 变量,以便在 IWindsorInstaller 方法运行之前就已分配该变量?
UPDATE
感谢 Slate 先生,但如果我这样做,这个控制器代码会是:
public DepartmentsController(IDepartmentRepository deptsRepository)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository");
}
_deptsRepository = deptsRepository;
}
...变得:
public DepartmentsController(IDepartmentRepository deptsRepository)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository");
}
_deptsRepository = deptsRepository(siteNum);
}
...or???
我仍然面临一个问题,即在 Castle Windsor / 控制器获取传入的 URI 之前,我应该在哪里拦截它,以便我可以为 global / siteNum var 设置适当的值?