Question

So, I've created a class that finds all classes in my project that implement a certain interface, generates instances of those classes then aggregates the results of a method provided from the contract of that interface.

Here is my code

    public string Parse(string src,JToken json)
    {
        var type = typeof(IReplaceTokens);
        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(t => type.IsAssignableFrom(t) && t.IsClass);

        return types.Select(tokenReplacer => Activator.CreateInstance(tokenReplacer) as IReplaceTokens)
            .Aggregate(src, (current, tokenReplacerInstance) => tokenReplacerInstance.ReplaceTokens(current, json));
    }

I'm getting MissingMethod exception methods from activator because it can't find a paramaterless constructor but the two parameters required by the constructors of these types should be injected by Ninject as they are bound.

From my NinjectModule

        Bind<IConfigReader>().To<JsonConfigReader>()
                             .InSingletonScope()
                             .WithConstructorArgument("appId", _appId)
                             .WithConstructorArgument("type", _type);

        var configReader = this.KernelInstance.GetService(typeof (IConfigReader)) as IConfigReader;
        if (configReader == null || configReader.JsonWrappedInExercise) { Bind<IJsonExtractor>().To<Pm3JsonExtractor>().InSingletonScope(); }
        else { Bind<IJsonExtractor>().To<NakedJsonExtractor>().InSingletonScope(); }

Signatures for all the Constructors Activator should be constructing

public MonthTokenReplacer(IJsonExtractor extractor, IConfigReader reader)
public DateTokenReplacer(IJsonExtractor extractor, IConfigReader reader)
public LastNameTokenReplacer(IJsonExtractor extractor, IConfigReader reader) : base(extractor, "[[LastName]]", reader.FirstNameField) { }
public TokenReplacerBase(IJsonExtractor extractor, string token,string objectKey)

Plus two others with parameterless constructors.

Any idea why this isn't working?

Was it helpful?

Solution

By calling Activator.CreateInstance you by pass Ninject like you do when using the new operator. You are responsible to provide any dependency yourself.

call kernel.Get(tokernReplacer) instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top