问题
In an app running Framework 4.72, not .NET Core, I'm trying to inject a SignalR IHubContext into a Web API 2.x service. I have my solution broken into three projects, web, service, data. The SignalR hub is in the web layer. I have background code that runs in the service layer and when complete I need it to send a mesage via the hub. This background task is not initiated by the controller.
My Global.asax is pretty standard:
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));
}
My DIConfig contains:
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);
}
And my 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);
});
}
}
The constructors of my service layer look like this:
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;
}
I know I need to pass an instance of the IHubContext into the service but so far I haven't been succesful. As I know, the first constructor is what is used when the service is called from anything other than the controller?
FIRST REVISION
Ok, I understand that everything should go into a single container. Based on feedback and looking at those links, I create a container and pass that along. Here is my revised 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);
}
}
And my AutofacConfig builds the container and does most of the registering:
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;
}
}
But, I still am not able to get the reference to the Hub in my Service (which is in a seperate project than the API but in the same solution.
My Service method is called from HangFire and has no reference to the Hub. How can I reference it in my parameterless constructor?
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;
}
}
回答1:
You can't resolve IHubContext
directly. But you can resolve generic implementation of this interface. More details described here and here.
I just create very simple implementation of OWIN
(Stratup.cs).
I have installed Autofac.SignalR nugget package and used method RegisterHubs for registration and method MapSignalR for mapping. It is standard approach and it is enghoy to resolve typed Hub implementation.
But if you wish resolve context more correct then you need to add two more registrations: AutofacDependencyResolver and ConnectionManager (more info available here).
Please review full sample:
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 is standard and simple:
public class MaintenanceHub : Hub
{
public MaintenanceHub(IMaintenanceLogProvider maintenanceLogProvider)
{
maintenanceLogProvider.TaskProgressStatusEvent += (s, e) => GetTaskLogStatus(e);
}
public void GetTaskLogStatus(LongTaskProgressStatus taskProgressStatus)
{
Clients.All.getTaskLogStatus(taskProgressStatus);
}
}
After registration you can use Hub inject context. Something like it (available 2 options, you can use only one what is you wish):
public AccountController(IConnectionManager connectionManager, MaintenanceHub maintenanceHub)
{
var context = connectionManager.GetHubContext<MaintenanceHub>();
var hub = maintenanceHub;
}
来源:https://stackoverflow.com/questions/64937202/inject-signalr-ihubcontext-into-service-layer-with-autofac