1

I have many classes with these implementations:

internal static class WindowsServiceConfiguration<T, Y> where T : WindowsServiceJobContainer<Y>, new() where Y : IJob, new()
{
    internal static void Create()
    {            
    }
}

public class WindowsServiceJobContainer<T> : IWindowsService where T : IJob, new()
{
    private T Job { get; } = new T();
    private IJobExecutionContext ExecutionContext { get; }

    public void Start()
    {

    }

    public void Install()
    {

    }

    public void Pause()
    {

    }

    public void Resume()
    {

    }

    public void Stop()
    {

    }

    public void UnInstall()
    {

    }
}

public interface IWindowsService
{
    void Start();
    void Stop();
    void Install();
    void UnInstall();
    void Pause();
    void Resume();
}

public class SyncMarketCommisionsJob : IJob
{                
    public void Execute(IJobExecutionContext context)
    {            
    }
}

public interface IJob
{     
    void Execute(IJobExecutionContext context);
}

I would like to call Create() method of WindowsServiceConfiguration static class by reflection as below:

WindowsServiceConfiguration<WindowsServiceJobContainer<SyncMarketCommisionsJob>, SyncMarketCommisionsJob>.Create();

and I don't know how to do that by using Activator or something like that in order to call Create method in my C# code?

best regards.

Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
  • Possible duplicate of [Call static method with reflection](https://stackoverflow.com/questions/11908156/call-static-method-with-reflection) – SᴇM May 21 '18 at 05:21
  • @SᴇM: The question is not a duplicate of [Call static method with reflection](https://stackoverflow.com/questions/11908156/call-static-method-with-reflection). That question is not about generic class. The answer is similar but not the same. – Eliahu Aaron Mar 01 '20 at 11:00

1 Answers1

2

Something like this ought to work:

// Get the type info for the open type
Type openGeneric = typeof(WindowsServiceConfiguration<,>);
// Make a type for a specific value of T
Type closedGeneric = openGeneric.MakeGenericType(typeof(WindowsServiceJobContainer<SyncMarketCommisionsJob>), typeof(SyncMarketCommisionsJob));
// Find the desired method
MethodInfo method = closedGeneric.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
// Invoke the static method
method.Invoke(null, new object[0]);
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86