unitycontainer / microsoft-dependency-injection

Unity.Microsoft.DependencyInjection package
Apache License 2.0
63 stars 36 forks source link

Unable to cast ServiceProvider to UnityContainer #22

Closed smadurange closed 6 years ago

smadurange commented 6 years ago

I have a .net core 2.1 console app. I'm building the container as below:

public IServiceProvider ConfigureServices()
{
    var services = new ServiceCollection();

    // Register services here.

    var containerFactory = new ServiceProviderFactory(null);
    var container = containerFactory.CreateBuilder(services);
    var serviceProvider = containerFactory.CreateServiceProvider(container);

    return serviceProvider;
}

After this, elsewhere I want to try and get the underlying unity container. I'm trying this:

IUnityContainer container = (UnityContainer) serviceProvider;

However, I'm getting the following error:

Unable to cast object of type 'Unity.Microsoft.DependencyInjection.ServiceProvider' to type 'Unity.UnityContainer'.

I verified in debug that the serviceProvider is available and all the services are registered properly at the cast site. However, the cast is not working.

ENikS commented 6 years ago

You cannot cast it, you need to resolve what you need

smadurange commented 6 years ago

@ENikS So, if I want to use Unity specific functionality that is not in IServiceProvider, how do I go about doing it? For example, do a parameter override for constructor args?

I'm currently doing:

public IUnityContainer ConfigureServices()
{
    var services = new ServiceCollection();

    // Register services here.

    var containerFactory = new ServiceProviderFactory(null);
    var container = containerFactory.CreateBuilder(services);

    return container;
}

This working. Please let me know if there's a better way to do this. Thanks