Search code examples
reflectionabstract-classnancy

Nancy and abstract base module class / creating phantom class instance


I'm building a small application with Nancy

I want to have a kind of base class, that other modules can inherit from.
See below (there is a reason this isn't an abstract class, which I'll explain below)

public class ImportModule<T> : NancyModule
{
    protected ImportModule()
        : this(typeof(T).Name.ToLower())
    {
        Get["/"] = _ => "need to select an action - xxx";
        Get["/importnew"] = _ => ImportNew(); //note - method omitted for brevity
    }
}

When I run my app, I get

Unable to resolve type: My.NameSpace.TypedImporter`1

As a sidenote, if the ImportModule class is abstract, this doesn't happen

Ok-
Now, I could have a class like this:

public class MyCustomImporter : ImportModule<MyCustomType>
{
   //overrides.... 
}

But, elsewhere, in a "DefaultImportModule" I have the following:

var importerModule = Activator.CreateInstance(typeof(ImportModule<>).MakeGenericType(type));

So I need to be able to create a type of importer, based on a type that's passed in

(Basically, if a user hits the url /customer, it's doing the same as a class like this would)

public class CustomerImporter : ImporterModule<Customer>
{
}

So, as I see it, I have two choices:
1) Stop nancy trying to map my ImportModule
2) Instantiate a "phantom class" that inherits from ImportModule and make ImportModule abstract again


Solution

  • There is a discussion in the Nancy group that may be related to your problem, it is certainly related to the non-abstract base modules not being recognised by Nancy. Here is what Andreas Håkansson had to say:

    Nancy locates everything that's inheriting NancyModule and assumes it's something it can instantiate. Nancy is aware that it cannot create an instance of an abstract module. So if you have a base-module that's not abstract then Nancy will attempt to new it up. I'd like to think that for 99% of the time, having a non-abstract base class is a broken design.

    And here is the link to the discussion:Unable to resolve type: Nancy.Routing.DefaultRouteResolver