3

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

Nancy.TinyIoc.TinyIoCResolutionException:无法解析类型:Plugin.HomeModule ---> 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 可以解决它?

4

3 回答 3

3

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

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

于 2014-02-25T09:56:22.060 回答
2

最好的方法是不要将原语传递到您的模块中,而是向我们传递更丰富的东西,或者可能是工厂。容器可以解决这些依赖关系。将纯字符串传递到模块中是其他地方出现问题的迹象,并暗示您的架构可能需要重新考虑

于 2014-02-25T13:46:29.100 回答
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;
}
于 2017-06-28T14:39:39.283 回答