1

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

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);
    }

和我刚刚从这里复制的 AutofacDependencyResolver :

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; }
    }
}

我的 HomeTasks 看起来像这样:

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

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

无法从程序集“SignalR,版本=0.5.1.10625,文化=中性,PublicKeyToken=null”加载类型“SignalR.Hosting.IRequest”。

编辑:

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

[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

4

1 回答 1

2

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

于 2012-07-13T06:28:01.630 回答