Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding Service from dynamically loaded Assembly to ServiceCollection?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading