What to use instead of HttpContext when using OWIN without System.Web
Asked Answered
B

2

3

We currently have a NancyFx project that we have wired up using OWIN. We are not using System.Web and we need some place to put our context that lives for the life of a request other than HttpContext. We have started implementing the context on a thread static variable so we can access the context anywhere in the application but we are worried that using Async calls will lose this thread static context.

What do you use as a static accessor in lue of HttpContext when you divorce yourself from System.Web?

Bosporus answered 22/5, 2014 at 18:9 Comment(0)
H
2

You can use the NancyContext instead. The Items dictionary on the NancyContext is for storing per-request objects. The NancyContext is available most anywhere in a Nancy application.

Henricks answered 22/5, 2014 at 18:59 Comment(7)
Can you statically access the NancyContext? We don't want to pass around the context to every single method we need it in.Bosporus
No, but it is available as a property on NancyModule, and as a parameter to Before, After, OnError hooks. Where do you need it from?Henricks
Currently we stuff things in the HttpContext about the state of the request and pull from that context anywhere in the application. We store non-business level objects in the HttpContext so we do not have to pass them around through every method we call. IIS manages the HttpContext per request so we always have a static accessor to our context from anywhere in the application.Bosporus
I guess you could get away with just passing the NancyContext around.Henricks
Making HttpContext.Current static was the worst thing MS ever did, so many poorly designed applications as a result...Dream
I haven't tested this out completely, but I'm trying to use Thread.SetData() and Thread.GetData() in order to store per requests objects. From what I understand .net spins up a new thread per request. Again, haven't tested this out fully, but hoping it will help.Collogue
@the pax bisonica: That depends on the host, and only works as long as your code doesn't switch thread e.g. by async/await.Henricks
A
1

This thread might answer your question : https://groups.google.com/forum/#!topic/nancy-web-framework/yILM4ZMrsSQ

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureRequestContainer(
        TinyIoCContainer container, NancyContext context)
    {
        base.ConfigureRequestContainer(container, context);
        container.Register<ICurrentRequest>(
          (c, o) => new CurrentRequest(context));
    }

    private class CurrentRequest : ICurrentRequest
    {
        public CurrentRequest(NancyContext context)
        {
            this.Context = context;
        }

        public NancyContext Context { get; private set; }
    }
}
Anticlimax answered 13/5, 2015 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.