How to dynamically build ctor

80 views Asked by At

I'm trying to generate a class at runtime, but I'm struggling to create the ctor.

I have a base class that looks like this:

public abstract class MyServiceBase : SomeOtherBaseClass
{
    private readonly ILogger _logger;
    private readonly IOptions<MyReaderOptions> _options;
    private readonly Extractor _extractor;
    private readonly IResolveSourceSystem _sourceSystemResolver;
    private readonly IAcceptLogs _logBuffer;

    protected MyServiceBase(ILogger logger,
                            IOptions<MyReaderOptions> options,
                            Extractor extractor,
                            IResolveSourceSystem sourceSystemResolver,
                            IAcceptLogs logBuffer)
    {
        _logger = logger;
        _options = options;
        _extractor = extractor;
        _sourceSystemResolver = sourceSystemResolver;
        _logBuffer = logBuffer;
    }

   // and then some public methods (not abstract - just normal implemented methods)

}

I would like to generate a class at runtime that looks like this:

public class MyGeneratedReader : MyServiceBase
{
    public MyGeneratedReader(ILogger<MyGeneratedReader> logger,
                            IOptions<MyReaderOptions> options,
                            Extractor extractor,
                            IResolveSourceSystem sourceSystemResolver,
                            IAcceptLogs logBuffer)
                            : base(logger, options, extractor, sourceSystemResolver, logBuffer)
    {

    }
}

So far, I can generate the class - but I'm struggling with adding the ctor.

I can get the base class'es ctorInfo (see below) - but I'm not sure how to add it to the new type and how to tell it that this should call the base class.


var newTypeName = "SomeReader";
var assemblyName = new AssemblyName("DynamicReaders");
var dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var dynamicModule = dynamicAssembly.DefineDynamicModule("Main");
var dynamicType = dynamicModule.DefineType(
    newTypeName,
    TypeAttributes.Public
        | TypeAttributes.Class
        | TypeAttributes.AutoClass
        | TypeAttributes.AnsiClass
        | TypeAttributes.BeforeFieldInit
        | TypeAttributes.AutoLayout,
    typeof(MyServiceBase));
);

var basector = typeof(MyServiceBase).GetConstructor(
        BindingFlags.NonPublic | BindingFlags.Instance,
        null,
        new[] { typeof(ILogger),
                typeof(IOptions<ReaderOptions>),
                typeof(JsonExtractor),
                typeof(IDetermineSourceSystem),
                typeof(ICanAcceptLogs)
               },
        null);
// At this point basector contains the info for the base classes ctor.
// Now what ???

var type = dynamicType.CreateType();


Any idea how I should add the ctor to my generated class so that it knows to call the base-class ctor ?

0

There are 0 answers