Wstaw SignalR IHubContext do warstwy usług za pomocą Autofac
W aplikacji z systemem Framework 4.72, a nie .NET Core, próbuję wstrzyknąć SignalR IHubContext do usługi Web API 2.x. Mam swoje rozwiązanie podzielone na trzy projekty, sieć, usługę, dane. Centrum SignalR znajduje się w warstwie internetowej. Mam kod w tle, który działa w warstwie usług i po zakończeniu potrzebuję go do wysłania wiadomości przez hub. To zadanie w tle nie jest inicjowane przez kontroler.
Mój Global.asax jest dość standardowy:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
// Set JSON serializer to use camelCase
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
DIConfig.Setup();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
var logConfigFilePath = Server.MapPath("~/log4net.config");
log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(logConfigFilePath));
}
Mój DIConfig zawiera:
internal static void Setup()
{
var config = System.Web.Http.GlobalConfiguration.Configuration;
var builder = new ContainerBuilder();
builder.Register(c => new ShopAPDbContext()).AsImplementedInterfaces().InstancePerBackgroundJob().InstancePerLifetimeScope();
builder.RegisterType<ShopAPRepository>().As<IShopAPRepository>().InstancePerBackgroundJob().InstancePerLifetimeScope();
builder.RegisterType<ShopAPService>().As<IShopAPService>().InstancePerBackgroundJob().InstancePerLifetimeScope();
builder.AddAutoMapper(typeof(InvoiceMappingProfile).Assembly);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(container);
}
I mój Startup.cs:
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = DependencyConfiguration.Configure(app);
SignalRConfiguration.Configure(app, container);
HangFireDashboardConfig.Configure(app);
}
}
public static class DependencyConfiguration
{
public static IContainer Configure(IAppBuilder app)
{
var builder = new ContainerBuilder();
builder.RegisterHubs(typeof(SignalRConfiguration).Assembly);
var container = builder.Build();
app.UseAutofacMiddleware(container);
return container;
}
}
public static class SignalRConfiguration
{
public static void Configure(IAppBuilder app, IContainer container)
{
HubConfiguration config = new HubConfiguration();
config.Resolver = new AutofacDependencyResolver(container);
app.Map("/messages", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJavaScriptProxies = false
};
map.RunSignalR(hubConfiguration);
});
}
}
Konstruktorzy mojej warstwy usług wyglądają następująco:
public ShopAPService()
{
_shopAPRepository = new ShopAPRepository();
_mapper = new Mapper((IConfigurationProvider)typeof(InvoiceMappingProfile).Assembly);
_hubContext = null; // what here?
}
public ShopAPService(IShopAPRepository shopAPRepository, IMapper mapper, IHubContext hubContext)
{
_shopAPRepository = shopAPRepository;
_mapper = mapper;
_hubContext = hubContext;
}
Wiem, że muszę przekazać wystąpienie IHubContext do usługi, ale jak dotąd nie udało mi się. Jak wiem, pierwszym konstruktorem jest to, co jest używane, gdy usługa jest wywoływana z czegokolwiek innego niż kontroler?
PIERWSZA WERSJA
Ok, rozumiem, że wszystko powinno trafić do jednego pojemnika. Opierając się na opiniach i patrząc na te linki, tworzę kontener i przekazuję go dalej. Oto mój poprawiony Startup:
public class Startup
{
public void Configuration(IAppBuilder app)
{
//var config = System.Web.Http.GlobalConfiguration.Configuration;
var container = GetDependencyContainer();
RegisterWebApi(app, container);
RegisterSignalR(app, container);
GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
HubConfiguration config = new HubConfiguration();
config.Resolver = new AutofacDependencyResolver(container);
//config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
Hangfire.GlobalConfiguration.Configuration.UseAutofacActivator(container);
HangFireDashboardConfig.Configure(app);
}
private IContainer GetDependencyContainer()
{
return AutofacConfig.RegisterModules();
}
private void RegisterWebApi(IAppBuilder app, IContainer container)
{
var configuration = new HttpConfiguration
{
DependencyResolver = new AutofacWebApiDependencyResolver(container)
};
WebApiConfig.Register(configuration);
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(configuration);
app.UseWebApi(configuration);
}
private void RegisterSignalR(IAppBuilder app, IContainer container)
{
var configuration = new HubConfiguration
{
Resolver = new AutofacDependencyResolver(container)
};
app.MapSignalR(configuration);
}
}
A moja AutofacConfig buduje kontener i wykonuje większość rejestracji:
internal class AutofacConfig
{
public static IContainer RegisterModules()
{
var builder = new ContainerBuilder();
builder.Register(c => new ShopAPDbContext()).AsImplementedInterfaces().InstancePerBackgroundJob().InstancePerLifetimeScope();
builder.RegisterType<ShopAPRepository>().As<IShopAPRepository>().InstancePerBackgroundJob().InstancePerLifetimeScope();
builder.RegisterType<ShopAPService>().As<IShopAPService>().InstancePerBackgroundJob().InstancePerLifetimeScope();
builder.RegisterAutoMapper(typeof(InvoiceMappingProfile).Assembly);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// Register Autofac resolver into container to be set into HubConfiguration later
builder.RegisterType<AutofacDependencyResolver>().As<IDependencyResolver>().SingleInstance();
// Register ConnectionManager as IConnectionManager so that you can get hub context via IConnectionManager injected to your service
builder.RegisterType<ConnectionManager>().As<IConnectionManager>().SingleInstance();
builder.RegisterHubs(Assembly.GetExecutingAssembly());
var container = builder.Build();
return container;
}
}
Ale nadal nie mogę uzyskać odwołania do centrum w mojej usłudze (która jest w osobnym projekcie niż interfejs API, ale w tym samym rozwiązaniu.

Moja metoda usługi jest wywoływana z HangFire i nie ma odniesienia do centrum. Jak mogę odwołać się do niego w moim konstruktorze bez parametrów?
public partial class ShopAPService : IShopAPService
{
private static readonly ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
readonly IShopAPRepository _shopAPRepository;
readonly IMapper _mapper;
private IHubContext _hubContext;
public ShopAPService()
{
_shopAPRepository = new ShopAPRepository();
_mapper = new Mapper((IConfigurationProvider)typeof(InvoiceMappingProfile).Assembly);
_hubContext = connectionManager.GetHubContext<MessageHub>();
}
public ShopAPService(IShopAPRepository shopAPRepository, IMapper mapper, IHubContext hubContext)
{
_shopAPRepository = shopAPRepository;
_mapper = mapper;
_hubContext = hubContext;
}
}
Odpowiedzi
Nie możesz rozwiązać IHubContext
bezpośrednio. Ale możesz rozwiązać ogólną implementację tego interfejsu. Więcej szczegółów opisanych tutaj i tutaj .
Po prostu tworzę bardzo prostą implementację OWIN
(Stratup.cs). Zainstalowałem pakiet nugget Autofac.SignalR i użyłem metody RegisterHubs do rejestracji i metody MapSignalR do mapowania. Jest to podejście standardowe i zachęcające do rozwiązywania problemów z implementacją typu Hub.
Ale jeśli chcesz, aby kontekst był bardziej poprawny, musisz dodać jeszcze dwie rejestracje: AutofacDependencyResolver i ConnectionManager (więcej informacji jest dostępnych tutaj ).
Zapoznaj się z pełną próbką:
using Autofac;
using Autofac.Integration.SignalR;
using Autofac.Integration.WebApi;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
using System.Reflection;
using System.Web.Http;
[assembly: OwinStartup(typeof(Startup))]
namespace Sample
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var container = GetDependencyContainer();
RegisterWebApi(app, container);
RegisterSignalR(app, container);
}
private IContainer GetDependencyContainer()
{
var builder = new ContainerBuilder();
AutofacConfig.RegisterModules(builder);
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterHubs(Assembly.GetExecutingAssembly());
// Register Autofac resolver into container to be set into HubConfiguration later
builder.RegisterType<AutofacDependencyResolver>().As<IDependencyResolver>().SingleInstance();
// Register ConnectionManager as IConnectionManager so that you can get hub context via IConnectionManager injected to your service
builder.RegisterType<ConnectionManager>().As<IConnectionManager>().SingleInstance();
var container = builder.Build();
return container;
}
private void RegisterWebApi(IAppBuilder app, IContainer container)
{
var configuration = new HttpConfiguration
{
DependencyResolver = new AutofacWebApiDependencyResolver(container)
};
WebApiConfig.Register(configuration);
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(configuration);
app.UseWebApi(configuration);
}
private void RegisterSignalR(IAppBuilder app, IContainer container)
{
var configuration = new HubConfiguration
{
Resolver = new AutofacDependencyResolver(container)
};
app.MapSignalR(configuration);
}
}
}
My Hub jest standardowe i proste:
public class MaintenanceHub : Hub
{
public MaintenanceHub(IMaintenanceLogProvider maintenanceLogProvider)
{
maintenanceLogProvider.TaskProgressStatusEvent += (s, e) => GetTaskLogStatus(e);
}
public void GetTaskLogStatus(LongTaskProgressStatus taskProgressStatus)
{
Clients.All.getTaskLogStatus(taskProgressStatus);
}
}
Po rejestracji możesz użyć kontekstu wstrzykiwania huba. Coś takiego (dostępne 2 opcje, możesz użyć tylko jednej, co chcesz):
public AccountController(IConnectionManager connectionManager, MaintenanceHub maintenanceHub)
{
var context = connectionManager.GetHubContext<MaintenanceHub>();
var hub = maintenanceHub;
}
