2015-07-20 64 views
2

我需要根据租户的owin值来解析DbContext。但是在Hub的方法OnDisconnected的管道中,HttpContext是not accessibleSignalR - 多租户依赖注入

我的HUB类:

public class UserTrackingHub : Hub 
{ 
    private readonly UserContext _context; 

    public UserTrackingHub(UserContext context) { ... } 

    public override async Task OnConnected() { /* OK HERE...*/ } 

    public override async Task OnDisconnected(bool stopCalled) 
    { 
     // NEVER FIRES WITH IF I USE THE CTOR INJECTION. 

     var connection = await _context.Connections.FindAsync(Context.ConnectionId); 
     if (connection != null) 
     { 
      _context.Connections.Remove(connection); 
      await _context.SaveChangesAsync(); 
     } 
    } 
} 

这里是我的Autofac配置:

public static IContainer Register(IAppBuilder app) 
    { 
     var builder = new ContainerBuilder(); 

     // Other registers... 

     builder.Register<UserContext>(c => 
     {  
      // Details and conditions omitted for brevity. 

      var context = HttpContext.Current; // NULL in OnDisconnected pipeline. 
      var owinContext = context.GetOwinContext(); 
      var tenant = owinContext.Environment["app.tenant"].ToString(); 
      var connection = GetConnectionString(tenant); 

      return new UserContext(connection); 
     }); 

     var container = builder.Build(); 
     var config = new HubConfiguration 
     { 
      Resolver = new AutofacDependencyResolver(container) 
     }; 

     app.MapSignalR(config); 

     return container; 
    } 

有人能帮我找出这个或任何其他方式OnDisconnected房客?
谢谢!

+0

你有没有找到一个解决办法?面对同样的问题。 –

+1

@ Jason.Net,我发布了在这里工作的解决方案。希望有所帮助! –

回答

2

任何有兴趣,我最终注入上下文工厂,而不是上下文本身:

public class UserTrackingHub : Hub 
{ 
    private readonly Func<string, UserContext> _contextFactory; 

    public UserTrackingHub(Func<string, UserContext> contextFactory) { ... } 

    public override async Task OnConnected() { ... } 

    public override async Task OnDisconnected(bool stopCalled) 
    { 
     var tenant = Context.Request.Cookies["app.tenant"].Value; 

     using (var context = _contextFactory.Invoke(tenant)) 
     { 
      var connection = await context.Connections.FindAsync(Context.ConnectionId); 
      if (connection != null) 
      { 
       context.Connections.Remove(connection); 
       await context.SaveChangesAsync(); 
      } 
     } 
    } 
} 

而且Autofac的配置:

// Resolve context based on tenant 
builder.Register<Func<string, UserContext>>(c => new Func<string, UserContext>(tenant => UserContextResolver.Resolve(tenant)));