为什么我不能让signalr与autofac依赖注入一起工作?

时间:2012-07-12 19:19:46

标签: autofac signalr

我是AutoFac的新手,但我认为这很简单。我有一个简单的Hub:

public class Chat : Hub
{
    private readonly IHomeTasks _homeTasks;
    public Chat(IHomeTasks homeTasks) 
    {
        _homeTasks = homeTasks;
    }

    public void Send(string text)
    {
        _homeTasks.DoNothing();
        Clients.addMessage(text);
        var user = new UserDocument { Username = text };
    }
}

在我的Global.ascx.cs中,我有:

    protected void Application_Start()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();

        builder.RegisterType<Helpers.AutofacDependencyResolver>().As<SignalR.IDependencyResolver>(); // Not sure if I need this or...

        var container = builder.Build();
        RouteTable.Routes.MapHubs(new Helpers.AutofacDependencyResolver(container));
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

和我刚从here复制的AutofacDependencyResol:

public class AutofacDependencyResolver : DefaultDependencyResolver, IRegistrationSource
{
    private readonly ILifetimeScope _lifetimeScope;

    public AutofacDependencyResolver(ILifetimeScope lifetimeScope)
    {
        _lifetimeScope = lifetimeScope;
        _lifetimeScope.ComponentRegistry.AddRegistrationSource(this);
    }

    public override object GetService(Type serviceType)
    {
        object result;
        if (_lifetimeScope.TryResolve(serviceType, out result))
        {
            return result;
        }

        return null;
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        object result;
        if (_lifetimeScope.TryResolve(typeof(IEnumerable<>).MakeGenericType(serviceType), out result))
        {
            return (IEnumerable<object>)result;
        }

        return Enumerable.Empty<object>();
    }

    public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
    {
        var typedService = service as TypedService;
        if (typedService != null)
        {
            var instance = base.GetServices(typedService.ServiceType);

            if (instance != null)
            {

                return instance.Select(i => RegistrationBuilder.ForDelegate(i.GetType(), (c, p) => i).As(typedService.ServiceType)
                    .InstancePerMatchingLifetimeScope(_lifetimeScope.Tag)
                    .CreateRegistration());
            }
        }

        return Enumerable.Empty<IComponentRegistration>();
    }

    bool IRegistrationSource.IsAdapterForIndividualComponents
    {
        get { return false; }
    }
}

My HomeTasks看起来像这样:

public class HomeTasks : Sandbox.Tasks.IHomeTasks
{
    public void DoNothing()
    {
    }
}

看起来没有任何事情发生,因为我在SignalR.Hosting.AspNet.HttpTaskAsyncHandler中收到这样的错误:

  

无法从程序集'SignalR加载'SignalR.Hosting.IRequest'类型,   Version = 0.5.1.10625,Culture = neutral,PublicKeyToken = null'。

修改

我删除了所有SignalR dll,然后由于dfowler的回答而重新添加,一切都很好但现在当我实际调用Chat Hub上的Send(文本)时,我得到了这个:

[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
   System.Activator.CreateInstance(Type type) +6
   SignalR.Hubs.DefaultHubActivator.Create(HubDescriptor descriptor) +141
   SignalR.Hubs.DefaultHubManager.ResolveHub(String hubName) +71
   SignalR.Hubs.HubDispatcher.CreateHub(IRequest request, HubDescriptor descriptor, String connectionId, TrackingDictionary state, Boolean throwIfFailedToCreate) +679
   SignalR.Hubs.HubDispatcher.OnReceivedAsync(IRequest request, String connectionId, String data) +870
   SignalR.<>c__DisplayClass6.<ProcessRequestAsync>b__4(String data) +73
   SignalR.Transports.ForeverTransport.ProcessSendRequest() +141
   SignalR.Transports.ForeverTransport.ProcessRequestCore(ITransportConnection connection) +128
   SignalR.Transports.ForeverTransport.ProcessRequest(ITransportConnection connection) +37
   SignalR.PersistentConnection.ProcessRequestAsync(HostContext context) +1018
   SignalR.Hubs.HubDispatcher.ProcessRequestAsync(HostContext context) +216
   SignalR.Hosting.AspNet.AspNetHandler.ProcessRequestAsync(HttpContextBase context) +676
   SignalR.Hosting.AspNet.HttpTaskAsyncHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +125
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8968180
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

我想我只是在这里错过了一件我无法弄清楚到底是什么。

是什么让我觉得SignalR的接线有问题是因为我还有一个工作正常的简单控制器。

public class HomeController : Controller
{
    private IHomeTasks _homeTasks;
    public HomeController(IHomeTasks homeTasks)
    {
        _homeTasks = homeTasks;
    }

    public ActionResult Index()
    {
        _homeTasks.DoNothing(); // No problems resolving HomeTasks!
    }

以答案更新

    protected void Application_Start()
    {
        var builder = new ContainerBuilder();
        builder.RegisterControllers(typeof(MvcApplication).Assembly);
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).AsImplementedInterfaces();
        builder.RegisterType<Chat>().InstancePerLifetimeScope();

        var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        RouteTable.Routes.MapHubs(new AutofacSignalrDependencyResolver(container));

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

使用上述AppStart方法。关键行是builder.RegisterType()。InstancePerLifetimeScope();.老实说,我不知道这是不是最好的方式,因为这对我来说是一种学习经历,因为我用我所知道的更好[Windsor]来解决这个问题,但我觉得我已经花了足够的时间来至少看到一些东西来自我的工作。希望这有助于某人:D

1 个答案:

答案 0 :(得分:2)

看起来版本不匹配,这可能是它无法加载类型的原因。确保使用二进制兼容版本的依赖项。