Dicekey
Dicekey

Reputation: 405

ASP.NET Core 2.1 unable to cast IServiceProvider

My application ASP.net web API project on core 2.1

I have the following IOC container class

// Ioc.cs
using Microsoft.Extensions.DependencyInjection;
using Rendigo.Core.Data;

public static class Ioc
{  
    public static RendigoContext RendigoContext => 
    IocContainer.Provider.GetService<RendigoContext>();
}

// IocContainer.cs
using Microsoft.Extensions.DependencyInjection;

public static class IocContainer
{
    public static ServiceProvider Provider { get; set; }
}

//startup.cs 


  public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
                    IServiceProvider serviceProvider)
    {
        // exception is raised here 
        IocContainer.Provider = (ServiceProvider)serviceProvider;
         var context = Ioc.RendigoContext;
    // .....
    }

The exception detail

System.InvalidCastException: 'Unable to cast object of type 'Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope' to type 'Microsoft.Extensions.DependencyInjection.ServiceProvider'.'

Upvotes: 1

Views: 2645

Answers (3)

Dawid Urban
Dawid Urban

Reputation: 1

I solved this problem like this:

IoCContainer.Provider = serviceProvider as ServiceProvider;

Upvotes: 0

Emmanuel Jay Bello
Emmanuel Jay Bello

Reputation: 1

IocContainer.Provider =(ServiceProvider) app.ApplicationServices;

hope this help...

Upvotes: -1

Nkosi
Nkosi

Reputation: 247008

  1. why i am getting this exception am i missing some code to place in program.cs or a library needs to be imported via nuget.

The error message tells you exactly what is the problem. The injected provider is of type ServiceProviderEngineScope but you are trying to cast it to ServiceProvider

  1. is this approach of making the context static is a good approach to follow

No.

You are basically creating a service locator, which is considered more of an anti-pattern. There should be no need to pass around the IServiceProvider as that should be the first indication of a code smell. It is advised you review your current design choices.

Consider practicing Explicit Dependency Principle

Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.

Upvotes: 2

Related Questions