Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Dependency Injection - Static Collection - Unclear of best practice

$
0
0

Hi all, I am new to working with .Net Core so please be gentle if my question is too simple. I have been tasked with rewriting an existing API service that contains 'x' number of predefined 'Jobs'  that can exist in one or more assemblies that make up the solution. 

In the current solution the list of available jobs is hard coded in a static class that can then be accessed from anywhere it is needed.

The requirement as part of my rewrite is to be able to generate the list of jobs dynamically by scanning the loaded assemblies and finding all 'Job' that derive from a specific Interface. Getting the list of jobs is not a problem. My problem is where best to put this functionality and register it in a .Net Core project.

I know I will be needing to use the Startup class to perhaps register a 'Singleton' class that contains this logic?

My basic understanding of the DI is that you register the Interface and the implementation type that it relates to. Now assuming I have the following example code;

class JobSingletonService
{
    private static IEnumerable<Type> jobs;

    private static readonly JobSingletonService _jobSingletonServiceInstance = new JobSingletonService();

    private JobSingletonService()
    {
          jobs = AppDomain.CurrentDomain.GetAssemblies()
                          .SelectMany(s => s.GetTypes())
                          .Where(p => typeof(IScheduledJob)
                          .IsAssignableFrom(p) && !p.IsInterface).ToList();

    }

    public static JobSingletonService GetInstance() => _jobSingletonServiceInstance;

    public IEnumerable<Type> GetJobs() => jobs;
}

I obviously only want to get a list of the available types once and as the app starts up BUT of the course I need somehow to make sure that all of the assemblies have actually loaded BEFORE executing this query?

So should I extract an Interface from this and register it for DI as a singleton?

Am I over thinking this? Do I just need to create a static class instead of a service?

Any assistance will be greatly appreciated, many thanks.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>