Home > Enterprise >  Adding Service from dynamically loaded Assembly to ServiceCollection?
Adding Service from dynamically loaded Assembly to ServiceCollection?

Time:12-13

maybe someone can help me out with this one:

I'm writing a Program, that dynamically loads assemblies that have different implementations of the same interface "IMyService". The case may occur, that some of the assemblies aren't even there (imagine this as a set of different modules of a software a user can buy... Some are bought, some aint, therefore the functionality isn't available and the dll isn't delivered).

So what I'm trying to do is the following:

private IServiceProvider ConfigureServices()
{
    const string vendor = "MyVendor";
    var assembly = Assembly.LoadFrom($"{vendor}.dll");
    var myVendorType = assembly.GetType($"{vendor}.Services.{vendor}Service");

    if (myVendorType == null) 
        throw new Exception($"Module '{vendor}' not found");


    var services = new ServiceCollection();
    // ... other services

    serviceCollection.TryAddSingleton<IMyService, myVendorType>();
    return serviceCollection.BuildServiceProvider();
}

Unfortunately this won't compile, since the IDE is telling me that it can't resolve the Symbol "myVendorType", when the Type is provided as the Implementation of the "TryAddSingleton..."

I know that the creation of an instance needs an Activator like so:

Activator.CreateInstance(myVendorType);

but, I have no idea what to do, when I want to provide the type to implement to the Service-Collection.

I hope someone has an idea :)

CodePudding user response:

As I mentioned in the comment you could register instance directly in service collection.

For that you could do services.TryAddSingleton<IMyService>(sp => (IMyService)Activator.CreateInstance(myVendorType))

Or even just services.TryAddSingleton<IMyService>( (IMyService)Activator.CreateInstance(myVendorType))

The first option is useful when you need to get something other from ServiceProvider to correctly instantiate the needed instance

  • Related