Using Simple Injector with SignalR

前端 未结 6 538
迷失自我
迷失自我 2020-12-04 10:50

I thought using my own IoC would be pretty straight forward with SignalR and maybe it is; most likely I\'m doing something wrong. Here\'s my code I have so far:



        
6条回答
  •  温柔的废话
    2020-12-04 11:25

    UPDATE This answer has been updated for SignalR version 1.0

    This is how to build a SignalR IDependencyResolver for Simple Injector:

    public sealed class SimpleInjectorResolver 
        : Microsoft.AspNet.SignalR.IDependencyResolver
    {
        private Container container;
        private IServiceProvider provider;
        private DefaultDependencyResolver defaultResolver;
    
        public SimpleInjectorResolver(Container container)
        {
            this.container = container;
            this.provider = container;
            this.defaultResolver = new DefaultDependencyResolver();
        }
    
        [DebuggerStepThrough]
        public object GetService(Type serviceType)
        {
            // Force the creation of hub implementation to go
            // through Simple Injector without failing silently.
            if (!serviceType.IsAbstract && typeof(IHub).IsAssignableFrom(serviceType))
            {
                return this.container.GetInstance(serviceType);
            }
    
            return this.provider.GetService(serviceType) ?? 
                this.defaultResolver.GetService(serviceType);
        }
    
        [DebuggerStepThrough]
        public IEnumerable GetServices(Type serviceType)
        {
            return this.container.GetAllInstances(serviceType);
        }
    
        public void Register(Type serviceType, IEnumerable> activators)
        {
            throw new NotSupportedException();
        }
    
        public void Register(Type serviceType, Func activator)
        {
            throw new NotSupportedException();
        }
    
        public void Dispose()
        {
            this.defaultResolver.Dispose();
        }
    }
    
    
    

    Unfortunately, there is an issue with the design of the DefaultDependencyResolver. That's why the implementation above does not inherit from it, but wraps it. I created an issue about this on the SignalR site. You can read about it here. Although the designer agreed with me, unfortunately the issue hasn't been fixed in version 1.0.

    I hope this helps.

    提交回复
    热议问题