Testura/Testura.Code

is it possible to integrate with a library project?

Closed this issue · 2 comments

for example, say i have a class library project. and i provide some abstract class called PersonBase and the consumers of my library will write derived classes such as JohnDoh and JaneDoh.

is it possible for me to (from my library code) generate a static class called AllPeople which would have a private field containing all derived types written by the consumer?

if so, could you pls point me in the right direction on how to achieve that?

maybe some sort of ms build task that does assembly scanning and calls new ClassBuilder() or something is needed?

wondering if your lib can be an easier alternative to the .net source code generators.

thanks!

It sounds like you want to work work with reflection. By reflection you can find every class that inherit from your base class and then use it to generate code. For example:

using System.Reflection.Emit;
using Testura.Code;
using Testura.Code.Builders;
using Testura.Code.Models;
using Testura.Code.Saver;

static IEnumerable<Type> GetAllTypesThatInheritFromAbstractClass<T>()
{
    return System.Reflection.Assembly.GetExecutingAssembly()
        .GetTypes()
        .Where(type => type.IsSubclassOf(typeof(T)));
}

var types = GetAllTypesThatInheritFromAbstractClass<PersonBase>();

var @class = new ClassBuilder("AllPeople", "MyNamespace", NamespaceType.FileScoped)
    .WithFields(types.Select(t => new Field(t.Name, t, new[] { Modifiers.Private })).ToArray())
    .Build();

var saver = new CodeSaver();
var generatedCode = saver.SaveCodeAsString(@class);

public abstract class PersonBase
{
}

public class JohnDoh : PersonBase
{
}

public class JaneDoh : PersonBase
{
}

Will generate:

namespace MyNamespace;

public class AllPeople
{
    private JohnDoh JohnDoh;
    private JaneDoh JaneDoh;
}

Something like that you are looking for?

thanks! will look in to that.