注册特定模块构造函数

时间:2014-02-25 09:37:17

标签: nancy tinyioc

我想在我的每个模块的结构中注入不同的字符串。我注册了一个构造模块的工厂方法。然后我可以打电话给container.Resolve<T>(),一切都很顺利。出于某种原因,虽然当Nancy试图解析我的模块时它会抛出错误

  

Nancy.TinyIoc.TinyIoCResolutionException:无法解析类型:   Plugin.HomeModule ---&gt; Nancy.TinyIoc.TinyIoCResolutionException:   无法解析类型:System.String

public class HomeModule : NancyModule
{
    public HomeModule(string text)
    {
    }
}

protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
    base.ConfigureApplicationContainer(container);
    container.Register<HomeModule>((ctr, param) => { return new HomeModule("text"); });
    HomeModule module = container.Resolve<HomeModule>();
}

我也尝试在ConfigureRequestContainer()中进行注册,结果相同。我尝试了container.Register<HomeModule>(new HomeModule("some text"));以及AsSingleton()。我可以使用container.Register<string>("text")向字符串类型注册实现,但这会将相同的字符串注入所有模块。

如何注册模块构造函数以便Nancy可以解决它?

3 个答案:

答案 0 :(得分:3)

模块是通过INancyModuleCatalog获得的,通常由引导程序实现,你必须创建一个自定义变体 - 如果你使用的是默认的bootstrapper,那么这就是当前的实现: / p>

https://github.com/NancyFx/Nancy/blob/master/src/Nancy/DefaultNancyBootstrapper.cs#L205

答案 1 :(得分:2)

对此最好的方法是不将原语传入您的模块,而是将更丰富的东西传递给工厂。容器可以解决这些依赖关系。将普通字符串传递到模块中是其他地方出现问题的迹象,并暗示您的体系结构可能需要重新思考

答案 2 :(得分:1)

我已经实现了一个自定义目录,它只注册特定命名空间的模块,但我不知道在哪里注册它。

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("MyCustomNamespace"));
        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;
}