Skip to content

Instantly share code, notes, and snippets.

@matthewvukomanovic
Last active January 7, 2023 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matthewvukomanovic/5f174946e21c4fe4e327ebc51fd7dc4a to your computer and use it in GitHub Desktop.
Save matthewvukomanovic/5f174946e21c4fe4e327ebc51fd7dc4a to your computer and use it in GitHub Desktop.
Autofac, OWIN, WebApi, and SignalR
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Autofac;
using Autofac.Integration.SignalR;
using Autofac.Integration.WebApi;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using Owin;
namespace ExampleMessageService
{
// Note run the following in the Package Manager Console to install required dependencies
// "Autofac.WebApi2.Owin", "Autofac.SignalR", "Microsoft.Owin.Cors","Microsoft.AspNet.SignalR.SelfHost", "Microsoft.Owin.SelfHost", "Microsoft.AspNet.WebApi.Owin" | foreach {install-package $_}
class Program
{
static void Main(string[] args)
{
using (WebApp.Start("http://*:5000", new Startup().Configuration))
{
Console.WriteLine("Press Enter to end service...");
Console.ReadLine();
}
}
}
public class Startup
{
/// <summary>
/// Perform the configuration
/// </summary>
/// <param name="app">The application builder to configure.</param>
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterModule(new ServiceModule());
var container = builder.Build();
var config = new HttpConfiguration
{
DependencyResolver = new AutofacWebApiDependencyResolver(container),
#if DEBUG
IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always,
#endif
};
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
app.UseWebApi(config);
var hubConfig = new HubConfiguration()
{
#if DEBUG
EnableDetailedErrors = true,
#endif
};
hubConfig.Resolver = container.Resolve<Microsoft.AspNet.SignalR.IDependencyResolver>();
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR("/signalr", hubConfig);
}
}
public class ServiceModule : Module
{
protected override void Load(ContainerBuilder builder)
{
// What ever registrations you need here
// IMessageService interacts with the hub
builder.RegisterType<MessageService>().As<IMessageService>();
// Register the controllers and the hubs
builder.RegisterApiControllers(typeof(ServiceModule).Assembly);
builder.RegisterHubs(typeof(ServiceModule).Assembly);
// Register the default Assembly Locator since otherwise the hub will no be created by Signalr correctly IF it is NOT in the entry executables assembly.
builder.RegisterType<DefaultAssemblyLocator>().As<IAssemblyLocator>();
// Register Autofac resolver into container to be set into HubConfiguration later
builder.RegisterType<Autofac.Integration.SignalR.AutofacDependencyResolver>()
.As<Microsoft.AspNet.SignalR.IDependencyResolver>()
.SingleInstance();
// Register ConnectionManager as IConnectionManager so that you can get
// hub context via IConnectionManager injected to your service
builder.RegisterType<Microsoft.AspNet.SignalR.Infrastructure.ConnectionManager>()
.As<Microsoft.AspNet.SignalR.Infrastructure.IConnectionManager>()
.SingleInstance();
}
}
public interface IMessageService
{
void BroadcastMessage(string message);
}
public class MessageService : IMessageService
{
private readonly IHubContext _hubContext;
public MessageService(IConnectionManager connectionManager)
{
_hubContext = connectionManager.GetHubContext<MessageHub>();
}
public void BroadcastMessage(string message)
{
_hubContext.Clients.All.Message(message);
}
}
public interface IMessage
{
void Message(string message);
}
public class MessageHub : Hub<IMessage>
{
private readonly ILifetimeScope _scope;
public MessageHub(ILifetimeScope scope)
{
_scope = scope;
}
public void Message(string message)
{
Clients.Others.Message(message);
}
public override Task OnConnected()
{
Clients.Others.Message("Client connected: " + Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stoppedCalled)
{
Clients.Others.Message("Client disconnected: " + Context.ConnectionId);
return base.OnDisconnected(stoppedCalled);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment