vendredi 5 juin 2020

Apply rules Generically on top of generics

I'm trying to make an mock data generator which will generate mocks based on a set of rules. I've been playing around with Bogus. I don't want to have to setup my rules for my entity classes each time, I would like to generically be able to apply rules to classes if they derrive from some interface.

Imagine I have entities which reuse a generic interface:

public interface IHasGeneric<T>
    where T : IHasGeneric<T>
{
    string Marker { get; set; }
}

public class Foo : IHasGeneric<Foo>
{
    public string Marker { get; set; }
}

public class Bar : IHasGeneric<Bar>
{
   public string Marker { get; set; }
}

Note: I'm aware this doesn't depict why I have a generic which takes in itself as a parameter. However, it takes too much to explain and cannot be changed from my architecture. So please work with it as a requirement.

Now I want to create a centralized Factory For Fakers, However I'm struggling to figure out how I can apply the rules generically to any type that is going to be generated.

public class MockDataGenerator
{
    public T Generate<T>()
        where T : class
    {
        var faker = new StatefulFaker<T>();
        this.ApplyDefaultRules<T>(faker);
    }

    public void ApplyDefaultRules<T>(StatefulFaker<T> faker)
        where T : class
    {
        //T Cannot be used as a type parameter 'T' ... No Implicit Conversion to IHasGeneric<T>
        if (typeof(T) is IHasGeneric<T>>)
        {

        }
    }
}

When trying to cast T to see if rules can be applied I get an error

T Cannot be used as a type parameter 'T' ... No Implicit Conversion to IHasGeneric. How can I generically apply rules to types which implement an interface?

Aucun commentaire:

Enregistrer un commentaire