Injecting IFilteredStream instance into SignalR Hub using Autofac

Apr 15, 2015 at 9:11 AM
I know that under the hood the Tweetinvi library uses autofac for some DI bits and pieces, but I haven't been able to figure out how to inject a singleton instance of the IFilteredStream / FilteredStream class into my SignalR Hub class.

I only want one instance of IFilteredStream running, and would like to be able to access the MatchingTweetReceived lambda function from my SignalR Hub:
public class TwitterHub : Hub
        private readonly ILifetimeScope _scope;
        private readonly TweetStream _stream;

        public TwitterHub(ILifetimeScope scope)
            _scope = scope.BeginLifetimeScope();

            _stream = scope.Resolve<TweetStream>();

            var i = _stream.Instance;

            i.MatchingTweetReceived += (sender, args) =>

My TweetStream class creates a singular FilteredStream instance and also performs all of the logic associated with connecting to the Twitter API:
public class TweetStream
        private IFilteredStream _stream;
        public TweetStream()
            var consumerKey = ConfigurationManager.AppSettings.Get("twitter:ConsumerKey");
            var consumerSecret = ConfigurationManager.AppSettings.Get("twitter:ConsumerSecret");
            var accessKey = ConfigurationManager.AppSettings.Get("twitter:AccessKey");
            var accessToken = ConfigurationManager.AppSettings.Get("twitter:AccessToken");

            TwitterCredentials.SetCredentials(accessKey, accessToken, consumerKey, consumerSecret);

            _stream = Stream.CreateFilteredStream();


        public IFilteredStream Instance
            get { return _stream; }

My OWIN Startup class, where I register the TweetStream class as a single instance, looks like this:
public class OwinStartup
        public void Configuration(IAppBuilder app)
            var builder = new ContainerBuilder();

            // use hubconfig, not globalhost
            var hubConfig = new HubConfiguration {EnableDetailedErrors = true};


            builder.Register(i => new TweetStream()).SingleInstance(); // right or wrong?

            var container = builder.Build();

            hubConfig.Resolver = new AutofacDependencyResolver(container);
            app.MapSignalR("/signalr", hubConfig);
I don't really know what I'm doing wrong, or even if I'm on the right track to ensuring only one instance of the stream to Twitter is open using Autofac, and being able to access the tweet received lambda from my SignalR Hub class.

Any help / suggestions would be very much appreciated!
Apr 15, 2015 at 3:14 PM

It has been a while that I have not worked with SignalR?
Can't you simply create a Singleton within your Hub?

Otherwise you should be able to register a single instance of an object like you did with autofac.

Marked as answer by linvi on 4/18/2015 at 4:42 AM