What will be the Autofac equivalent for this Ninject code?

On the following page: http://www.asp.net/signalr/overview/signalr-20/extensibility/dependency-injection

Next to the bottom (just below the text "RegisterHubs.Start") is a snippet of Ninject code that I'm trying to reproduce using Autofac.

So far I have managed to give a headache, but not much more. I looked at the Autofac wiki files and web pages for some help. Although, I'm sure that I probably missed some tidbits of information.

Refresh . Here is the relevant Ninject code on the page.

public static class RegisterHubs { public static void Start() { var kernel = new StandardKernel(); var resolver = new NinjectSignalRDependencyResolver(kernel); kernel.Bind<IStockTicker>() .To<Microsoft.AspNet.SignalR.StockTicker.StockTicker>() .InSingletonScope(); kernel.Bind<IHubConnectionContext>().ToMethod(context => resolver.Resolve<IConnectionManager>(). GetHubContext<StockTickerHub>().Clients ).WhenInjectedInto<IStockTicker>(); var config = new HubConfiguration() { Resolver = resolver }; App.MapSignalR(config); } } 

Update 2 . I think I will also add objects to be compiled.

 public class StockTickerHub : Hub { private readonly IStockTicker _stockTicker; public StockTickerHub(IStockTicker stockTicker) { } } public class StockTicker { public StockTicker(IHubConnectionContext clients) { } } 
+7
c # ninject autofac signalr
source share
1 answer

Autofac has no equivalent to the WhenInjectedInto method. However, you can accomplish the same thing using named parameters.

Try something like this

 using Autofac.Integration.SignalR; using Microsoft.AspNet.SignalR.StockTicker; public static class RegisterHubs { public static void Start() { var builder = new ContainerBuilder(); builder.RegisterType<StockTicker>() .WithParameter(ResolvedParameter.ForNamed("StockTickerContext")) .As<IStockTicker>() .SingleInstance(); builder.Register(c => GlobalHost.DependencyResolver.Resolve<IConnectionManager>().GetHubContext<StockTickerHub>().Clients) .Named<IHubConnectionContext>("StockTickerContext"); var container = builder.Build(); var resolver = new AutofacDependencyResolver(container); var config = new HubConfiguration { Resolver = resolver }; App.MapSignalR(config); } } 

Note. AutofacDependencyResolver comes from Autofac.Integration.SignalR .

Update : Ah, I missed a tiny detail from the linked page; the factory function for IHubConnectionContext uses a converter to get the IConnectionManager , not the container itself (of course, the container will not know about IConnectionManager ). I switched to using the default dependency GlobalHost.DependencyResolver ( GlobalHost.DependencyResolver ) to get an IConnectionManager instead. That should work.

+11
source share

All Articles