I have an ASP.NET MVC5 application with SignalR and Ninject for dependency injection. I have a special authorize attribute for a web request and a signalr hub request.
I made the following class for the network:
public class MyWebAuthorizeAttribute : AuthorizeAttribute
{
[Inject]
public IMyService MyService { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var id = int.Parse((httpContext.Handler as MvcHandler).RequestContext.RouteData.Values["id"].ToString());
if (!MyService.Exists(id))
return false;
return base.AuthorizeCore(httpContext);
}
}
And for SignalR:
public class MySignalRAuthorizeAttribute : AuthorizeAttribute
{
[Inject]
public IMyService MyService { get; set; }
public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
{
var id = int.Parse(request.QueryString["id"]);
if (!MyService.Exists(id))
return false;
return base.AuthorizeHubConnection(hubDescriptor, request);
}
}
Ninject associations in the Startup class:
var kernel = new StandardKernel();
var resolver = new NinjectSignalRDependencyResolver(kernel);
kernel.Bind<IMyService>().To<MyService>().InSingletonScope();
var config = new HubConfiguration();
config.Resolver = resolver;
app.MapSignalR(config);
The problem is that the service is not entered in MySignalRAuthorizeAttribute, although the service is correctly entered in MyWebAuthorizeAttribute.
Any idea what I'm missing to get this to work?
Edit:
Found a way to more or less work.
In the startup class, I had to add this:
GlobalHost.DependencyResolver = resolver;
And then in MySignalRAuthorizeAttribute I could get a service like this:
MyService = GlobalHost.DependencyResolver.Resolve<IMyService>();
This works, but I would rather just get the service injected with the [Inject] attribute.