arex388 / Arex388.AspNet.Mvc.Startup

ASP.NET MVC "classic" dependency injection and service configuration extensions to simulate ASP.NET Core's Startup configuration
MIT License
8 stars 3 forks source link

Configure ServiceProvider before Configure(IAppBuilder) #4

Closed dahlbyk closed 3 years ago

dahlbyk commented 3 years ago

I've finally started using this in the project I mentioned in #1, and ran into an issue wiring up Hangfire.NetCore to use DI for job activation. Specifically, services.AddHangfire(...) doesn't execute custom configuration until an IGlobalConfiguration is resolved. This is verified for full ASP.NET Core, but I had to figure that out the hard way.

Anyway, to fix this I needed access to the IServiceProvider, which wasn't exposed anywhere. To that end, this PR includes two important changes:

  1. The IServiceProvider and methods to work with it have moved from private in ServiceScopeModule to public in StartupApplication
  2. The IServiceProvider is now automatically built before Configure(IAppBuilder), as also happens in the ASP.NET Core hosting lifecycle.
    • I've marked ConfigureServices() as [Obsolete].

I also included a few bonus changes, including:

  1. Added .editorconfig to enforce non-VS-default code standards (K&R braces, using order)
  2. Wiring up the MVC DependencyResolver now happens in AddControllers(), as the resolver is useless if the controllers haven't been registered.

For reference, this is an abbreviated version of what my Hangfire.NetCore config now looks like:

        public override void Configure(IAppBuilder app)
        {
            // Force initialization before we start server
            ServiceProvider.GetRequiredService<IGlobalConfiguration>();

            app.UseHangfireDashboard();

            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                // Uses AspNetCoreJobActivator registered by services.AddHangfire()
                Activator = ServiceProvider.GetService<JobActivator>(),
            });
        }

        public override void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(config => { /* ... */ })
        }
dahlbyk commented 3 years ago

PR has been updated onto latest master

arex388 commented 3 years ago

Version 1.0.5 should be available shortly on NuGet with the changes. Thanks for contributing!

arex388 commented 3 years ago

@dahlbyk, thanks to your example of configuring HangFire above, I was able to overhaul my implementation and reduce it down to 1/5th of what it was and remove all the weird hacks I had to put in when I first implemented this library. Now, I'm basically word-for-word as far as code is concerned with what I would do in an ASP.NET Core application. Thanks!

arex388 commented 3 years ago

@dahlbyk, can I get your thoughts on #5?