我有一个使用NancyFx的asp.net应用程序。我想根据数据库中的许可证仅注册特定模块。这是因为模块具有基于不同配置的相同路由。
所以我认为你应该创建实现INancyModuleCatalog的自定义类。
public class CustomModuleCatalog:INancyModuleCatalog { 私人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;
}
}
如何在我的Bootstrapper中注册此目录?
答案 0 :(得分:1)
boostrapper也是INancyModuleCatalog的实现(假设您正在使用DefaultNancyBootstrapper),请参阅此处的第97行:https://github.com/NancyFx/Nancy/blob/master/src/Nancy/DefaultNancyBootstrapper.cs#L97
我相信您还需要创建自己的引导程序来注册自己的目录。
但是 - 你需要提供自己的目录吗?您是否可以根据许可证类型检查可以切换的模块构造函数中的许可证类型,并仅在适用时注册其路由?
例如
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" });
}
}