I have an asp.net application that uses NancyFx. I want to register only specific modules based on licenses in my database. This is because the modules have the same routes based on different configurations.
So I thought you should have to create your custom class that implements INancyModuleCatalog.
public class CustomModuleCatalog : INancyModuleCatalog { private IDictionary _modules;
public CustomModuleCatalog()
{
// The license type is read from db in Global.ascx.
// So I want to register a module based on a namespace.
// The namespace is the same like the license name.
if(WebApiApplication.LicenseType == LicenseType.RouteOne)
{
var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
var modules = assemblyTypes.Where(t => t.Namespace != null && t.Namespace.EndsWith(WebApiApplication.SystemType.ToString()));
var nancy = modules.Where(t => t.IsAssignableFrom(typeof(INancyModule)));
foreach (var type in nancy)
{
var nancyType = (INancyModule)type;
_modules.Add(type, (INancyModule)Activator.CreateInstance(type));
}
}
}
public IEnumerable<INancyModule> GetAllModules(NancyContext context)
{
return _modules?.Values;
}
public INancyModule GetModule(Type moduleType, NancyContext context)
{
if (_modules != null && _modules.ContainsKey(moduleType))
{
return _modules[moduleType];
}
return null;
}
}
How to register this catalog in my Bootstrapper ?
The boostrapper is also the implementation of INancyModuleCatalog (assuming you're using the DefaultNancyBootstrapper) see line 97 here: https://github.com/NancyFx/Nancy/blob/master/src/Nancy/DefaultNancyBootstrapper.cs#L97
I believe you would need to create your own bootstrapper as well to register your own catalog.
But - do you need to provide your own catalog? Could you not just do the check of the license type in the constructor of the modules that can be switched out based on license type and only register their routes if applicable?
eg;
public class RouteOne : NancyModule
{
public RouteOne()
{
if (xxx.License != LicenseType.RouteOne) return;
Get["/"] = _ => Response.AsJson(new {Message = "This is route one"});
}
}
public class RouteTwo : NancyModule
{
public RouteTwo()
{
if (xxx.License != LicenseType.RouteTwo) return;
Get["/"] = _ => Response.AsJson(new { Message = "This is route two" });
}
}