我想弄清楚 NancyFx 请求容器是如何工作的,所以我创建了一个小测试项目。
我创建了一个这个界面
public interface INancyContextWrapper
{
NancyContext Context { get; }
}
有了这个实现
public class NancyContextWrapper : INancyContextWrapper
{
public NancyContext Context { get; private set; }
public NancyContextWrapper(NancyContext context)
{
Context = context;
}
}
然后在引导程序中我像这样注册它
protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
base.ConfigureRequestContainer(container, context);
container.Register<INancyContextWrapper>(new NancyContextWrapper(context));
}
我在一个除了将请求 url 作为字符串返回之外什么都不做的类中使用这个上下文包装器。
public interface IUrlString
{
string Resolve();
}
public class UrlString : IUrlString
{
private readonly INancyContextWrapper _context;
public UrlString(INancyContextWrapper context)
{
_context = context;
}
public string Resolve()
{
return _context.Context.Request.Url.ToString();
}
}
最后在模块中使用它
public class RootModule : NancyModule
{
public RootModule(IUrlString urlString)
{
Get["/"] = _ => urlString.Resolve();
}
}
当我这样做时,请求始终为空。现在我或多或少可以弄清楚,由于IUrlString
没有在请求容器配置中配置,因此 TinyIocINancyContextWrapper
在发出任何请求之前在应用程序启动时解析,并且 TinyIoc 不会重新注册依赖关系图依赖于在请求容器配置。
我的问题是使用 ConfigureRequestContainer 的最佳做法是什么?我是否必须在请求容器配置中注册以任何方式显式依赖 NancyContext 的所有内容?这很快就会变得臃肿且难以维护。我喜欢 TinyIoc 进行程序集扫描的方式,所以不得不这样做有点受挫。