Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dependency Injection Runtime (dynamic) registration

I am using VS 2017 and .NET Core. Using Dependency Injection, I would like to register my service at runtime, dynamically. My goal is to write instances of my service that implement the service interface inside of separate assemblies. The servicename/assembly name will then be added to some sort of configuration file (or db table).

My registration code would do something like this:

var ServiceTypeName = LoadServiceAssembly(AssemblyName); 

var serviceProvider = new ServiceCollection()
 .AddTransient<IDILogger, "ConsoleDILogger">()  // <--- Goal
 .BuildServiceProvider();

var logger = serviceProvider.GetService(IDILogger);

Clearly, the AddTransient line will not work as such a method does not exist. It does, however, depict the idea. I want to register the type by a string name so that the loader application need not be recompiled everytime I add a new service type.

I cannot seem to find how to do this. Any suggestions would be welcome.

TIA

like image 810
xgp Avatar asked Mar 13 '18 17:03

xgp


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


2 Answers

That's obviously not possible as is, however, I used something similar to this in a project to avoid having to add each new type to the container:

var assembly = typeof(YourClass).Assembly; // I actually use Assembly.LoadFile with well-known names 
var types = assembly.ExportedTypes
   // filter types that are unrelated
   .Where(x => x.IsClass && x.IsPublic);

foreach (var type in types)
{
    // assume that we want to inject any class that implements an interface
    // whose name is the type's name prefixed with I
    services.AddScoped(type.GetInterface($"I{type.Name}"), type);
}

For your specific case, you could even make this shorter:

var type = assembly.ExportedTypes.First(x => x.Name == runtimeName);
services.AddScoped(typeof(IDILogger), type);
like image 80
Camilo Terevinto Avatar answered Oct 08 '22 20:10

Camilo Terevinto


You could read configured type from the settings, load the required type via reflection and register it in service collection:

//  Read from config
var assemblyPath = "...";
var typeName = "...";

var assembly = Assembly.LoadFrom(assemblyPath);
var loggerType = assembly.GetType(typeName);

var serviceProvider = new ServiceCollection()
    .AddTransient(typeof(IDILogger), loggerType)
    .BuildServiceProvider();

var logger = serviceProvider.GetService<IDILogger>();

Such dynamic approach will not require any recompilation if you add or reconfigure new logger.

like image 25
CodeFuller Avatar answered Oct 08 '22 21:10

CodeFuller