ASP.NET Web API应用程序中的Autofac多租户IoC容器

前端之家收集整理的这篇文章主要介绍了ASP.NET Web API应用程序中的Autofac多租户IoC容器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Autofac 3.0现在将获得 MultitenantIntegration支持its preview release is out.为了试用它,我使用以下配置创建了一个ASP.NET Web API应用程序:
  1. public class Global : System.Web.HttpApplication {
  2.  
  3. protected void Application_Start(object sender,EventArgs e) {
  4.  
  5. var config = GlobalConfiguration.Configuration;
  6. config.Routes.MapHttpRoute("Default","api/{controller}");
  7. RegisterDependencies(config);
  8. }
  9.  
  10. public void RegisterDependencies(HttpConfiguration config) {
  11.  
  12. var builder = new ContainerBuilder();
  13. builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
  14.  
  15. // creates a logger instance per tenant
  16. builder.RegisterType<LoggerService>().As<ILoggerService>().InstancePerTenant();
  17.  
  18. var mtc = new MultitenantContainer(
  19. new RequestParameterTenantIdentificationStrategy("tenant"),builder.Build());
  20.  
  21. config.DependencyResolver = new AutofacWebApiDependencyResolver(mtc);
  22. }
  23. }

它完成了工作,并为每个租户创建一个LoggerService实例作为ILoggerService.在这个阶段我有两个问题,我无法解决

>我在这里提供了开箱即用的RequestParameterTenantIdentificationStrategy作为TenantIdentificationStrategy,仅用于此演示应用程序.我可以通过实现ITenantIdentificationStrategy接口来创建我的自定义TenantIdentificationStrategy.但是,ITenantIdentificationStrategy的TryIdentifyTenant方法使您依赖于静态实例,例如HttpContext.Current,这是我在ASP.NET Web API环境中不需要的东西,因为我希望我的API能够托管不可知(我知道我可以将此工作委托给托管层,但我宁愿不这样做.有没有其他方法可以实现这一点,我不会依赖静态实例?
>我也有机会注册租户特定实例如下:

  1. mtc.ConfigureTenant("tenant1",cb => cb.RegisterType<Foo>()
  2. .As<IFoo>().InstancePerApiRequest());

但是,我的一个情况要求我通过构造函数参数传递租户名称,我希望有类似下面的内容

  1. mtc.ConfigureTenant((cb,tenantName) => cb.RegisterType<Foo>()
  2. .As<IFoo>()
  3. .WithParameter("tenantName",tenantName)
  4. .InstancePerApiRequest());

目前没有这样的API.有没有其他方法来实现这一点或这种要求没有任何意义?

解决方法

多租户支持已经有很长一段时间了,只是3.0是我们第一次使用NuGet包.

猜你在找的asp.Net相关文章