Skip to content

Problem in registering IHubContext<,> in Grace IOC #229

Closed

Description

@shahabganji

Question on stackoverflow

I have a 2.2 .net core application, using SignalR core, in one of my Controllers I want to inject IHubContext<ChatHub, IChatClient>. Works pretty well with built-in IoC, but when I add Grace IoC I get the following error message:

Unable to resolve service for type 'Microsoft.AspNetCore.SignalR.IHubContext`2[Test.Hubs.ChatHub,Test.Hubs.IChatClient]' while attempting to activate TestController

I tried to add the following line in the ConfigureContainer method:

scope.Configure(c=> c.Export<IHubContext<ChatHub, IChatClient>>());

Also tried:

scope.Configure(c=> { c.Export(typeof(IHubContext<,>)); });

Then the error changed to the following which sounds reasonable since I haven't registered a concrete class for the interface.

Could not find public constructor on type Microsoft.AspNetCore.SignalR.IHubContext`2[[Test.Hubs.ChatHub, Test, Version=0.0.1.0, Culture=neutral, PublicKeyToken=null],[Test.Hubs.IChatClient, Test, Version=0.0.1.0, Culture=neutral, PublicKeyToken=null]]

And BTW, I've tested aforementioned approaches with both
.UseGrace((new InjectionScopeConfiguration { AutoRegisterUnknown = true })) and .UseGrace((new InjectionScopeConfiguration { AutoRegisterUnknown = false })).

Grace.AspNetCore.MVC and Grace.AspNetCore.Hosting packages are installed.

Anything that I missed?

Activity

  1. silkfire commented on Jul 24, 2019

    @silkfire
    Contributor

    I think you need to add scope.SetupMvc() in order for Grace to correctly perform injection on your controllers.

  2. shahabganji commented on Jul 24, 2019

    @shahabganji
    Author

    I testes that as well but to no avail.

    Program.cs

    // omitted code
    WebHost.CreateDefaultBuilder(args)
    .UseGrace((new InjectionScopeConfiguration { AutoRegisterUnknown = false }));

    Startup.cs

     public void ConfigureContainer(IInjectionScope scope)
            {
                scope.SetupMvc();
            }

    Got the following error

    An unhandled exception has occurred while executing the request.
    System.ArgumentNullException: Value cannot be null.
    Parameter name: instance
       at Microsoft.Extensions.Internal.PropertyActivator`1.Activate(Object instance, TContext context)
       at Microsoft.AspNetCore.Mvc.Internal.DefaultControllerPropertyActivator.<>c__DisplayClass5_0.<GetActivatorDelegate>g__Activate|0(ControllerContext controllerContext, Object controller)
       at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    __ EDIT __

    And with

    .UseGrace((new InjectionScopeConfiguration { AutoRegisterUnknown = true }));

    Got this one:

    An unhandled exception has occurred while executing the request.
    Grace.DependencyInjection.Exceptions.LocateException: Could not locate Type Microsoft.AspNetCore.SignalR.IHubContext`2[Test.Hubs.ChatHub,Test.Hubs.IChatClient]
    1 Importing Test.Controllers.GroupsController
    2 Importing Microsoft.AspNetCore.SignalR.IHubContext`2[Test.Hubs.ChatHub,Test.Hubs.IChatClient]  for constructor parameter chatHub
    
       at Grace.DependencyInjection.Impl.InjectionContextValueProvider.GetValueFromInjectionContext[T](IExportLocatorScope locator, StaticInjectionContext staticContext, Object key, IInjectionContext dataProvider, Object defaultValue, Boolean useDefault, Boolean isRequired) in C:\projects\grace\src\Grace\DependencyInjection\Impl\InjectionContextValueProvider.cs:line 236
       at lambda_method(Closure , IExportLocatorScope , IDisposalScope , IInjectionContext )
       at Grace.DependencyInjection.Impl.ActivationStrategyDelegateCache.FallbackExecution(ImmutableHashTree`2 currentNode, Type type, IExportLocatorScope scope, Boolean allowNull, IInjectionContext context) in C:\projects\grace\src\Grace\DependencyInjection\Impl\ActivationStrategyDelegateCache.cs:line 128
       at Grace.DependencyInjection.Impl.ActivationStrategyDelegateCache.ExecuteActivationStrategyDelegateAllowNull(Type type, IExportLocatorScope scope) in C:\projects\grace\src\Grace\DependencyInjection\Impl\ActivationStrategyDelegateCache.cs:line 78
       at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  3. ipjohnson commented on Jul 24, 2019

    @ipjohnson
    Owner

    Hi @shahabganji

    Could you put together a small sample of it not working and I can take a look. What it sounds like is there is a registration that's not being added to Grace but is to the default container (not sure how that happens).

    I've not worked with SignalR before so I'm not 100% sure what's wrong.

  4. silkfire commented on Jul 24, 2019

    @silkfire
    Contributor

    I assume you've added this as well to your code to activate SignalR?

    app.UseSignalR(routes => routes.MapHub<MyHubType>("/hub-endpoint"));

  5. shahabganji commented on Jul 24, 2019

    @shahabganji
    Author

    Hi @ipjohnson, yes sure I'll try to reproduce the problem in a repository and I will share the link here.

    @silkfire your assumption is correct.

  6. shahabganji commented on Jul 24, 2019

    @shahabganji
    Author

    @ipjohnson here you could find a sample repo.

    Just one thing to note, due to this I thought that version 7.1 might be only for .net core 3.0, however, I tested the above-mentioned repo with both versions 6.4 and 7.1.

  7. ipjohnson commented on Jul 31, 2019

    @ipjohnson
    Owner

    @shahabganji sorry it's taken me so long to get to this I've been swamped with life stuff.

    When I open this project it fails to load with this exception

    'C:\Users\ijohnson\Documents\Visual Studio 2019\Projects\GraceSignalRSample-master\GraceSignalRSample\GraceSignalRSample.csproj : error : One or more errors occurred.'

  8. shahabganji commented on Jul 31, 2019

    @shahabganji
    Author

    @ipjohnson

    Don't be, take your time.

    I created the project on my Mac, but I get the same error on windows too; 😩 let me check it first.

  9. shahabganji commented on Jul 31, 2019

    @shahabganji
    Author

    @ipjohnson

    It should be OK now, just needed to remove global.json file 🙈

  10. ipjohnson commented on Aug 1, 2019

    @ipjohnson
    Owner

    So I took a look and there is a bug in the way the generic type is being constructed (or not constructed as the case is). I'm going to try and address this issue and a couple others this weekend.

  11. changed the title [-][QUESTION]: How to register IHubContext<,> in Grace IOC[/-] [+]Problem in registering IHubContext<,> in Grace IOC[/+] on Aug 1, 2019
  12. ipjohnson commented on Aug 5, 2019

    @ipjohnson
    Owner

    I have one more issue I need to address before I can do a beta release but you can test the fix in the nightly nuget feed

    https://ci.appveyor.com/nuget/grace-master

  13. shahabganji commented on Aug 5, 2019

    @shahabganji
    Author

    @ipjohnson

    Thanks for your great support. Unfortunately, my laptop is broken and I cannot test it until I get it repaired. however, as soon as I have my machine I will test and report the results. 🙏

  14. 9 remaining items

  15. ipjohnson commented on Aug 26, 2019

    @ipjohnson
    Owner

    Ok I can reproduce it. My unit test was slightly different than the use case. It's an easy fix but I won't be able to do it till tomorrow or Wednesday

  16. ipjohnson commented on Aug 28, 2019

    @ipjohnson
    Owner

    I just pushed a new beta can you try it

  17. shahabganji commented on Aug 28, 2019

    @shahabganji
    Author
  18. ipjohnson commented on Aug 28, 2019

    @ipjohnson
    Owner

    I ran it in the example you provided but better to have you test it as well

  19. shahabganji commented on Aug 28, 2019

    @shahabganji
    Author

    Hi @ipjohnson

    I got a chance to test the project and here is the result:

    • When scope.SetupMvc() is not called inside ConfigureContainer method, it works fine.
    • When it is called without Action<GraceMVCConfiguration>, it fails with the same error.
    • When it is called with Action<GraceMVCConfiguration> and the UseControllerActivator prop is set to false again works fine, but when set to true it fails again.
    public void ConfigureContainer( IInjectionScope scope ) {
                scope.SetupMvc((config) =>
                {
                    config.UseControllerActivator = false; // Works fine
    //               config.UseControllerActivator = true; // Will fail if commented out
                } );
            }
    <PackageReference Include="Grace" Version="7.1.0-Beta772" />
  20. cuteant commented on Aug 28, 2019

    @cuteant

    Thanks!!!
    After this bug is fixed, Grace can run perfectly in OrchardCore

  21. ipjohnson commented on Aug 28, 2019

    @ipjohnson
    Owner

    @shahabganji when I run it in the example app it's working so I'm a little unsure why it's not working. Can screen shot the error again and send me the program.cs and startup.cs?

    @cuteant you're running into this same issue in OrchardCore?

  22. cuteant commented on Aug 28, 2019

    @cuteant

    Yes, but the problem I encountered was that when the GraphQL Type field was registered, I found that IOptions<> could not be resolved correctly.

  23. ipjohnson commented on Aug 28, 2019

    @ipjohnson
    Owner

    @cuteant do you have a simple example of this or something you could share that I can run?

  24. cuteant commented on Aug 28, 2019

    @cuteant

    OrchardCore.ShellContainerFactory

    Replace with this:
    `
    public static IServiceProvider BuildGraceServiceProvider(this IServiceCollection services)
    {
    var configuration = new InjectionScopeConfiguration();
    configuration.AutoRegisterUnknown = false;
    configuration.Behaviors.AllowInstanceAndFactoryToReturnNull = true;
    return BuildGraceServiceProvider(services, configuration);
    }

        public static IServiceProvider BuildGraceServiceProvider(this IServiceCollection services, IInjectionScopeConfiguration configuration)
        {
            if (configuration is null) { Eme.EmeThrowHelper.ThrowArgumentNullException(Eme.ExceptionArgument.configuration); }
    
            var container = new DependencyInjectionContainer(configuration);
            return container.Populate(services);
        }
    

    `
    The test case in OrchardCore.Test cannot pass

    My english is not so good, I hope you can understand

  25. shahabganji commented on Aug 28, 2019

    @shahabganji
    Author

    @shahabganji when I run it in the example app it's working so I'm a little unsure why it's not working. Can screen shot the error again and send me the program.cs and startup.cs?

    @cuteant you're running into this same issue in OrchardCore?

    Worth to mention that I am running the app on a Mac.

    Program.cs

    public class Program
        {
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().Run();
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>()
                    .UseGrace(new InjectionScopeConfiguration
                    {
                        AutoRegisterUnknown = false
                    })
            ;
        }

    Startup.cs

    public class Startup {
            public Startup( IConfiguration configuration ) {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices( IServiceCollection services ) {
                services.AddSignalR( );
    
                services.AddMvc( ).SetCompatibilityVersion( CompatibilityVersion.Version_2_2 );
            }
    
            public void ConfigureContainer( IInjectionScope scope ) {
                scope.SetupMvc((config) =>
                {
                    config.UseControllerActivator = true; // set this to false, or totally forget scope.SetupMvc
                } );
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure( IApplicationBuilder app, IHostingEnvironment env ) {
                if ( env.IsDevelopment( ) ) {
                    app.UseDeveloperExceptionPage( );
                } else {
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts( );
                }
    
                app.UseSignalR( routes => { routes.MapHub<ChatHub>( "/hubs/chat" ); } );
    
                app.UseHttpsRedirection( );
                app.UseMvc( );
            }
        }

    Screenshot of the Browser

    Screen Shot 2019-08-28 at 23 42 59


    Raw Exception Details

    System.ArgumentNullException: Value cannot be null.
    Parameter name: instance
       at Microsoft.Extensions.Internal.PropertyActivator`1.Activate(Object instance, TContext context)
       at Microsoft.AspNetCore.Mvc.Internal.DefaultControllerPropertyActivator.<>c__DisplayClass5_0.<GetActivatorDelegate>g__Activate|0(ControllerContext controllerContext, Object controller)
       at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
       at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  26. ipjohnson commented on Aug 29, 2019

    @ipjohnson
    Owner

    @shahabganji this is caused by a combination of AutoRegisterUnknown = false and config.UseControllerActivator = true;

    Essentially you're telling the container not to auto register unknown types (controller specifically) and you're enabling resolving controllers from the container. If you register all your controllers and other concrete types then you can use that combination of flags. Otherwise you'll need to change something.

    @cuteant your issue looks to be different and I'm planning on addressing it this weekend as I have a couple days off.

  27. ipjohnson commented on Sep 9, 2019

    @ipjohnson
    Owner

    I think this can be closed out and I'll push an RC version here this week

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions