Setting up SignalR with Castle Windsor is relatively straight forward. This is after I messed around trying to get it work for a while. The example setup in this blog is using SignalR 2, Owin and Castle Windsor.
The example contains a hub which provides random numbers to clients, not very exciting but should hopefully be useful enough for this example. The hub code is as follows.
[HubName("randomNumberHub")]
public class RandomNumberHub : Hub
{
private readonly ILogger _log;
public IRandomNumberGenerator Generator { get; set; }
public RandomNumberHub(ILogger logger)
{
_writer = writer;
}
public void GetRandomNumber()
{
_logger.Log("Get Random Number Called");
Clients.All.updateRandomNumber(Generator.Random());
}
}
In the example above we have provided IRandomNumberGenerator public property as we want to make sure that property inject is working and also ILogger which is provided through the constructor.
Now we need to provide a custom Dependency Resolver which we will provide when configuring SignalR in the “startup.cs”.
public class SignalRDependencyResolver : DefaultDependencyResolver
{
private readonly IWindsorContainer _container;
public SignalRDependencyResolver(IWindsorContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
_container = container;
}
public override object GetService(Type serviceType)
{
return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : base.GetService(serviceType);
}
public override IEnumerable<object> GetServices(Type serviceType)
{
return _container.Kernel.HasComponent(serviceType) ? _container.ResolveAll(serviceType).Cast<object>() : base.GetServices(serviceType);
}
}
The above class is from the signalR.Castle.Windsor nuget package which can be found here Nuget Package. Although if you don’t want to install the package just use the code above.
We now have to provide a HubConfiguration for when we map SignalR in the startup class.
private static HubConfiguration CreateHubConfiguration()
{
var signalrDependency = new SignalRDependencyResolver(_container);
var configuration = new HubConfiguration { Resolver = signalrDependency };
return configuration;
}
Here we are setting the Hub Configurations resolver to our SignalRDependencyResolver.
The last step is to now provide our HubConfiguration when we Map SignalR which is nice and simple.
app.MapSignalR(CreateHubConfiguration());
That’s it, all done.