Home > Mobile >  Dependency Injection was working, now isn't
Dependency Injection was working, now isn't

Time:12-02

I've been setting up some code to manage redirects in an ASPNET Core project. The redirect/di code I set up as a POC was working and so I went on to code the DB parts of the system. On returning my DI has stopped working... Can anyone explain to me what's going on?

The code below is an approximate example of what I've done (it's been simplified so hopefully it is still a fair representation of what i'm trying to achieve... I've included the output I'm getting at the end so you can see where the problem is...

Thanks in advance!

Dan

------------- Main Project Startup.cs -------------

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        Console.WriteLine("xxxx about to services.AddRedirections()");
        services.AddRedirections();
        Console.WriteLine("xxxx done services.AddRedirections()");
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ConfigureRewriteMiddleware(app, requestLocalizationOptions);
    }

    private void ConfigureRewriteMiddleware(IApplicationBuilder app, RequestLocalizationOptions requestLocalizationOptions)
    {
        app.UseCustomRedirectsRewriter();
    }
}

------------- Redirect Project ServiceCollectionExtensions.cs -------------

public static class ServiceCollectionExtensions
{
    public static void AddRedirections(this IServiceCollection serviceCollection)
    {
        Console.WriteLine("xxxx AddRedirections");
        serviceCollection.AddSingleton<IRedirectsService, RedirectsService>();
    }
}

------------- Main Project CustomRedirectsRewriter.cs -------------

public static class CustomRedirectsRewriter
{
    public static void UseCustomRedirectsRewriter(this IApplicationBuilder app)
    {
        var customRedirects = new CustomRedirects();
        var customRedirectsOptions = new RewriteOptions().Add(customRedirects.ProcessRedirects);
        app.UseRewriter(customRedirectsOptions);
    }
}

------------- Main Project CustomRedirects.cs -------------

public class CustomRedirects
{
    private IRedirectsService _redirectsService;

    public CustomRedirects()
    {
        Console.WriteLine("xxxx CustomRedirects()");
        var services = new ServiceCollection();
        var serviceProvider = services.BuildServiceProvider();

        try
        {
            _redirectsService = serviceProvider.GetRequiredService<IRedirectsService>();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message   " xxxxxx "   ex.StackTrace);
        }

        if (_redirectsService == null) Console.WriteLine("xxxx redirectsService is null in CustomRedirects()");
    }

    public async void ProcessCustomRedirects(RewriteContext rewriteContext)
    {
        if (_redirectsService == null)
        {
            //I added additional attempts to reinitialize service later in code
            Console.WriteLine("xxxx redirectsService is null in ProcessCustomRedirects() and wasn't initalized in constructor");
            try
            {
                var services = new ServiceCollection();
                var serviceProvider = services.BuildServiceProvider();
                _redirectsService = serviceProvider.GetRequiredService<IRedirectsService>();
            }
            catch (Exception ex)
            {
                Console.WriteLine("xxxx redirectsService is still null in ProcessCustomRedirects() after second attempt");
            }
        }

        if (_redirectsService != null)
        {
            //do redirects
        }
    }
}

------------- Redirect Project RedirectsService.cs -------------

public class RedirectsService : IRedirectsService
{
    public RedirectsService() {}

    public async Task<List<RedirectModel>> GetRedirectsForDomain(string domain)
    {
        var redirectsList = new List<RedirectModel>();
        return redirectsList;
    }
}

------------- Redirect Project IRedirectsService.cs -------------

public interface IRedirectsService
{
    Task<List<RedirectModel>> GetRedirectsForDomain(string domains);
}

------------- OUTPUT -------------

xxxx about to services.AddRedirections()
xxxx AddRedirections
xxxx done services.AddRedirections()
xxxx CustomRedirects()

No service for type 'IRedirectsService' has been registered. xxxxxx at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

xxxx redirectsService is null in CustomRedirects()
xxxx redirectsService is null in ProcessCustomRedirects() and wasn't initalized in constructor
xxxx redirectsService is still null in ProcessCustomRedirects() after second attempt

CodePudding user response:

So you are using a locally initiated service collection

var services = new ServiceCollection();
.
. 
.
 _redirectsService = serviceProvider.GetRequiredService<IRedirectsService>();//The collection is just initiated and not containing any IRedirectsService resolution

and not the app service collection that you registered RedirectsService. You may pass app.Services to CustomRedirects contractor and use that to resolve the service.

  • Related