Instantiate a ServiceCollection object in Powershell

63 Views Asked by At

I need to use dependency injection in a Powershell script so I started creating a ServiceCollection instance with this snippet code:

clear

# Load the assemblies
Add-Type -Path "C:\MyDlls\Microsoft.Extensions.DependencyInjection.dll"
Add-Type -Path "C:\MyDlls\Microsoft.Extensions.DependencyInjection.Abstractions.dll"

# Now, you can use types from the loaded assemblies
$serviceCollection = New-Object -TypeName Microsoft.Extensions.DependencyInjection.ServiceCollection

# Example: Add a service to the collection
$serviceCollection.AddSingleton([YourNamespace.YourServiceType])

# Example: Build the service provider
$serviceProvider = $serviceCollection.BuildServiceProvider()

However, I got the following exceptions:

Add-Type : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
At line:5 char:1
+ Add-Type -Path "C:\MyDlls ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : NotSpecified: (:) [Add-Type], ReflectionTypeLoadException
  + FullyQualifiedErrorId : System.Reflection.ReflectionTypeLoadException,Microsoft.PowerShell.Commands.AddTypeCommand


New-Object : Cannot find type [Microsoft.Extensions.DependencyInjection.ServiceCollection]: verify that the assembly containing this type is loaded.
At line:9 char:22
 + ... ollection = New-Object -TypeName Microsoft.Extensions.DependencyInjec ...
 +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

So, what's missing in my script? Did anyone face the same issue? Thanks

0

There are 0 best solutions below