0

I'm still just getting back into the swing of things in .NET (took a 6 year hiatus) and am running into a problem which I feel I am close to solving, but can't quite get there.

What I'm trying to do is refactor some code I wrote that does some setup various parts of a service. The code is pretty repetitive and I have to do a similar thing in another place so I thought I would make it more generic. Right now I am doing something like:

public void InitConfiguration()
{
  ...
  myservice.AddPart(s =>
  {
    s.ShouldDoStuff = true;
    s.MethodWithGeneric<SomeType>();
  }

    myservice.AddPart(s =>
  {
    s.ShouldDoStuff = false;
    s.MethodWithGeneric<SomeOtherType>();
  }
  // do this 5 more times
}

So.. my approach was to create a MyConfigCollection class that has a List of IMyConfig objects that have the members I need to do .AddPart() on my service:

interface IMyConfig
{
    public bool ShouldDoStuff {get; set;}
    public Type FooType {get;}
}

public class MyConfig<TFooType> : IMyConfig
{
    public bool ShouldDoStuff {get; set;}
    public Type FooType {get {return typeof(TFooType);}}
}

public class MyConfigCollection
{
   public List<IMyConfig> MyConfigs {get; set;}
}

It sort of started smelling weird to me when I realized I had to make an interface for a config then implement it with a generic type param in order to have a List of MyConfig with different types. Then when I tried to use it:

public void InitConfiguration(IConfigCollection configurations)
{
    foreach ( IMyConfig config in configurations)
    {
        myservice.AddPart(s => 
        {
            s.ShouldDoStuff = config.ShouldDoStuff;
            // I can't do this!!!
            s.MethodWithGeneric<config.FooType>();
        });
    }
}

Righhtt I can't do that. I understand generics are intended to be set at compile type so it's a code smell to try and make them dynamic. The api of myservice is not something I can change (third party) I also am not sure what approach I could take here to achieve my goal. I feel like this is a solved problem and there exists a best practice for situations like this but my Google-fu has failed me. Could anyone suggest an approach I could take here? How could I trim down the duplication I am doing(and will have to do again) and make this a bit more flexible? Any advice is appreciated. Thanks!

TheMethod
  • 2,893
  • 9
  • 41
  • 72
  • 3
    Maybe you should take a look at [this question](https://stackoverflow.com/questions/232535/how-do-i-use-reflection-to-call-a-generic-method) on calling a generic method by using reflection. You just need to "build" a generic method during runtime based on your `config.FooType` value. – vinicius.ras Nov 22 '18 at 16:12
  • Yes, you can use reflection to invoke generic method with dynamic type parameter. But there are, i believe, better alternatives. I suggest this one:https://gist.github.com/jesuslpm/f93f9bcc4d3f3578cc97900a24339a34 – Jesús López Nov 22 '18 at 16:40

0 Answers0