2014-10-17 112 views
2

我有一個「服務」類,它在我的Nancy模塊外執行某些邏輯。服務類在容器中註冊,以便我可以通過構造器注入來訪問模塊中的實例。如果我的類依賴於NanyContext,我如何從模塊外部訪問它?訪問模塊外的NancyContext

回答

3

NancyContext是爲每個請求創建的,因此如果您的服務範圍不超過請求,那麼只需要依賴它即可。否則,您必須將NancyContext中的方法調用傳遞給您的服務。

如果該服務具有請求範圍,你可以創建並在BootstrapperConfigureRequestContainer註冊它:

public class Bootstrapper : DefaultNancyBootstrapper 
{ 
    protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context) 
    { 
     var service = new Service(context); 
     container.Register(service); 
     base.ConfigureRequestContainer(container, context); 
    } 
} 
+0

我可以用這個'container.Register(上下文);'? – 2015-02-23 17:24:00

+0

你可以,是的。 – 2015-02-23 17:58:47

+0

但似乎我不能。出錯。最後,我將'NancyContext'封裝到'MyContext'中,然後從'MyContext'暴露一些輔助函數。這對我很好。謝謝! – 2015-02-24 17:22:21