Session icon indicating copy to clipboard operation
Session copied to clipboard

Getting the ISession injected

Open leonardlabat opened this issue 10 years ago • 11 comments

Hello,

Is it possible to imagine that ISession can be directly registered in the DI container ? Perhaps throught a factory that use the ISessionFeature ? This is only to lighten syntax while using session. The HttpContext is not really testable and I think that injecting an ISession into my controller would be much easier than injecting ISessionFeature to finally get the ISession.

Thanks

leonardlabat avatar Jan 30 '16 20:01 leonardlabat

I'm 1000% for this behavior (see https://github.com/aspnet/HttpAbstractions/issues/488). Do you have any code samples showing how you're testing session right now?

davidfowl avatar Jan 30 '16 21:01 davidfowl

That'how my tests are looking with session out of the box


public class HomeControllerTests
{
    [Fact]
    public void GetCorrectValueFromSession()
    {
        var session = new Mock<ISession>();
        byte[] bytes = Encoding.UTF8.GetBytes("leo");
        session.Setup(x => x.TryGetValue("userName", out bytes));

        var homeController = new HomeController(new SessionFeature { Session = session.Object });

        var result = homeController.Index();
        Assert.NotNull(result);
        var jsonResult = result as JsonResult;
        Assert.NotNull(jsonResult);
        var name = jsonResult.Value as string;
        Assert.NotNull(name);
        Assert.Equal("leo", name);
    }
}

That's how I want it to look like


public class HomeControllerTests
{
    [Fact]
    public void GetCorrectValueFromSession()
    {
        var session = new Mock<ISession>();
        byte[] bytes = Encoding.UTF8.GetBytes("leo");
        session.Setup(x => x.TryGetValue("userName", out bytes));

        var homeController = new HomeController(session.Object);

        var result = homeController.Index();
        Assert.NotNull(result);
        var jsonResult = result as JsonResult;
        Assert.NotNull(jsonResult);
        var name = jsonResult.Value as string;
        Assert.NotNull(name);
        Assert.Equal("leo", name);
    }
}

And how I'm achieving it


services.AddTransient(typeof(ISession), serviceProvider =>
{
    var sessionFeature = serviceProvider.GetService<ISessionFeature>();
    return sessionFeature.Session;
});

Thanks

leonardlabat avatar Jan 30 '16 21:01 leonardlabat

This looks pretty wrong:

services.AddTransient(typeof(ISession), serviceProvider =>
{
    var sessionFeature = serviceProvider.GetService<ISessionFeature>();
    return sessionFeature.Session;
});

How does that even work? There's no ISessionFeature service in the DI container. Do you have a working application somewhere? (preferably github)

davidfowl avatar Jan 30 '16 21:01 davidfowl

Oh... I tried to do it by memory and I got wrong. I'm doing it throught the IHttpContextAccessor. But I you really plan to remove it from the HttpContext, the trick won't work anymore.


        services.AddTransient(typeof(ISession), serviceProvider =>
        {
            var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
            return httpContextAccessor.HttpContext.Session;
        });

leonardlabat avatar Jan 30 '16 21:01 leonardlabat

@davidfowl, @leonardlabat's use of IHttpContextAccessor is about the only way to implement this. Session requires access to request and response cookies and state (e.g. has the response started yet).

Tratcher avatar Jan 30 '16 23:01 Tratcher

@davidfowl Do you still want this?

muratg avatar Feb 02 '16 22:02 muratg

@davidfowl :question:

muratg avatar Feb 29 '16 22:02 muratg

@davidfowl Putting this in backlog. We can discuss later if we want to do something around this.

muratg avatar Mar 16 '16 17:03 muratg

Can close

davidfowl avatar Mar 16 '16 17:03 davidfowl

What about registering a factory that will get the session via the IHttpContextAccessor?

services.AddScoped(sp => sp.GetService<IHttpContextAccessor>().HttpContext.Session);

Is this safe to do? I'm wondering if there's some gotcha with the sync context/task scheduler/etc that would cause me to get the wrong user's session. 😨

If this is viable, one could depend on ISession directly and simplify their code / tests.

ronnieoverby avatar Nov 02 '18 16:11 ronnieoverby

Sure it's fine as long as you access it when the HttpContext is valid.

davidfowl avatar Nov 02 '18 17:11 davidfowl