我正在Web应用程序中使用Ninject。
代码:
public interface ICustomerService
{}
public class CustomerService : ICustomerService
{
public CustomerService(IContext context)
{
/*Code*/
}
}
public interface IContext
{}
public class Context : IContext
{
public Context(IApplicationContext applicationContext)
{
/*Code*/
}
}
public class TestController : Controller
{
public TestController(IContext context, ICustomerService customerService)
{
/*Code*/
}
}
public class TestApiController : ApiController
{
public TestController(IContext context, ICustomerService customerService)
{
/*Code*/
}
}
public partial class MyHub : Hub
{
public MyHub(IContext context, ICustomerService customerService)
{
/*Code*/
}
}
Ninject绑定:
kernel.Bind<IApplicationContext>().ToMethod(context => { return HttpContext.Current.GetOwinContext().Get<IApplicationContext>();}).InRequestScope();
kernel.Bind<IContext>().To<Context>().InRequestScope();
kernel.Bind<ICustomerService>().To<CustomerService>().InRequestScope();
我的服务已正确绑定,并使用InRequestScope()注入了Mays控制器和ApiControllers
但是对于信号中心,InRequestScope仅在连接情况下有效,而在断开连接情况下(HttpContext.Current = null)有效。
我对绑定范围做了一些修改
kernel.Bind<IHermesApplicationContext>().ToMethod(context => {
IApplicationContext applicationContext = HttpContext.Current?.GetOwinContext().Get<IApplicationContext>();
return applicationContext ?? new UnknownApplicationContext();
}).InRequestScope();
在那种情况下(集线器断开连接),我的上下文不是实例化的单个实例。
实施此方法有什么好的做法?
谢谢