我想弄清楚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();
}
}
当我这样做时,请求始终为null。现在我可以或多或少地弄清楚,由于IUrlString
未在请求容器配置中配置,因此TinyIoc在应用程序启动之前解决了INancyContextWrapper
,并且在发出任何请求之前,TinyIoc不会重新注册依赖关系依赖图依赖于请求容器配置中配置的内容。
我的问题是使用ConfigureRequestContainer的最佳做法是什么?我是否必须在请求容器配置中注册以任何方式明确依赖NancyContext的所有内容?这很快就会变得臃肿,难以维持。我喜欢TinyIoc如何进行组装扫描,所以不得不这样做有点挫折。
答案 0 :(得分:4)
假设上面的例子只是对你真正想要的东西的简化 - 也就是说在某些目的的请求生命周期中携带nancy上下文的东西,你可能最好不要使用引导程序,因为它是取决于使用的IoC容器。
建议:
更改包装器的实现以不使用ctor,而是使用属性设置器(您始终可以编码,以便只能设置属性一次):
public interface INancyContextWrapper
{
NancyContext Context { get; set; }
}
public class NancyContextWrapper : INancyContextWrapper
{
private NancyContext _context;
public NancyContext Context
{
get {return _context;}
set {_context = value;} //do something here if you want to prevent repeated sets
}
}
不使用容器和引导程序直接使用IRegistration实现(这些实现由nancy使用,并且与容器无关)
public class NancyContextWrapperRegistrations : IRegistrations
{
public IEnumerable<TypeRegistration> TypeRegistrations
{
get
{
return new[]
{
new TypeRegistration(typeof(INancyContextWrapper), typeof(NancyContextWrapper), Lifetime.PerRequest),
new TypeRegistration(typeof(IUrlString .... per request
};
// or you can use AssemblyTypeScanner, etc here to find
}
//make the other 2 interface properties to return null
}
}
使用IRequestStartup任务(这些也由nancy自动发现)来设置上下文
public class PrepareNancyContextWrapper : IRequestStartup
{
private readonly INancyContextWrapper _nancyContext;
public PrepareNancyContextWrapper(INancyContextWrapper nancyContext)
{
_nancyContext = nancyContext;
}
public void Initialize(IPipelines piepeLinse, NancyContext context)
{
_nancyContext.Context = context;
}
}
虽然上面看起来有点过分,但是以IoC独立方式组织类型注册是非常好的方法(例如,如果用其他东西替换TinyIoC,则不需要触摸bootstrappers等)。
此外,它是一种非常好的方法来控制请求期间(或者如果你想要 - 应用程序)启动时发生的事情,没有覆盖引导程序中的任何内容,它将适用于你决定去的任何引导程序/容器。< / p>