AppHost does not support accessing the current Request via a Singleton

Since we moved from version .54 to .60 in our Unit Tests the error started to appear

AppHost does not support accessing the current Request via a Singleton

But, works fine on production … so I just want to fix the unit tests…
from an old answer, it seems we should pass the request, but the error is thrown when converting the current session into a the session object:

public object Get(GetActivitiesInformation request)
{
    var session = SessionAs<MitivoApiAuthSession>();
    ...

with the trace

System.NotImplementedException : This AppHost does not support accessing the current Request via a Singleton
   at ServiceStack.HostContext.GetCurrentRequest()
   at ServiceStack.SessionFeature.GetOrCreateSession[T](ICacheClient cache, IRequest httpReq, IResponse httpRes)
   at ServiceStack.Service.SessionAs[TUserSession]()
   at Mitivo.Services.Services.ActivityService.Get(GetActivitiesInformation request) in D:\Repositories\Mitivo_back_end\code\Mitivo.Services\Services\ActivityService.cs:line 48
   at Mitivo.UnitTests.Services.ActivityServiceTest.CanGetActivities() in D:\Repositories\Mitivo_back_end\code\Mitivo.UnitTests\Services\ActivityServiceTest.cs:line 67

What do I have to do in my ServiceTEstBase to avoid this exception?

current:

    [TestFixtureSetUp]
    protected void ServiceTestFixtureSetUp()
    {
        AppHost = new BasicAppHost(typeof(BoostService).Assembly)
        {
            ConfigureContainer = container =>
            {
                //Set JSON web services to return idiomatic JSON camelCase properties
                // make servicestack use structure map as the adapter as we can the reuse the IoC container from Gko lib init
                container.Adapter = new StructureMapContainerAdapter();
                //Set JSON web services to return idiomatic JSON camelCase properties
                JsConfig.EmitCamelCaseNames = true;
                JsConfig.DateHandler = DateHandler.ISO8601;
                JsConfig.IncludeNullValues = true;

                // Memory cache
                container.RegisterAs<MemoryCacheClient, ICacheClient>();

                var userRep = new MitivoUserAuthRepository(container.Resolve<NHibernate.ISessionFactory>(), container.Resolve<IMitivoUserPasswordProvider>());
                container.Register<IUserAuthRepository>(userRep);
                container.Register<IRoleValidator>(new RoleValidator());

                container.RegisterAutoWiredAs<RewardHelper, IRewardHelper>();
                container.RegisterAutoWiredAs<LogActionLogger, ILogActionLogger>();
                container.Register(A.Fake<ILoggerFactory>());
            }
        }
            .Init();
        Container = ServiceStackHost.Instance.Container;
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
        AppHost.Dispose();
    }

Did you try to use req.SessionAs<MitivoApiAuthSession>() instead of SessionAs<MitivoApiAuthSession>() where req is IRequest?

If this does not work for you can you post small standalone project, which shows the issue?

issue is that this.Request (ServiceStack.Service.Request) is null as the test (as set in my question as ServiceTestFixtureSetUp.AppHost is created in memory… so there’s no Request available.

Working finr on .54 though :confused:

But I’ll try to make a small solution to test this outsite all dependencies I have in my own solution. Will reply.

OK, We’ll wait a sample from you and will look into it.

You should still be injecting a Mock Request into the Service if you’re going to execute it, e.g:

var service = new MyService { Request = new MockHttpRequest() };

that was it, but because I’m using a custom AuthSession I’m getting

System.InvalidCastException : Unable to cast object of type ‘ServiceStack.AuthUserSession’ to type ‘Mitivo.Services.Authentication.MitivoApiAuthSession’.

more stack

at ServiceStack.SessionFeature.GetOrCreateSession[T](ICacheClient cache, IRequest httpReq, IResponse httpRes)
at ServiceStack.Service.SessionAs[TUserSession]()

my setup is:

[SetUp]
protected void ServiceTestSetUp()
{
    Service = ServiceStackHost.Instance.Resolve<T>();
    Service.Request = new MockHttpRequest();

    MitivoApiAuthSession = new MitivoApiAuthSession
    {
        CurrentCompany = Session.Get<Company>(1),
        CurrentUser = Session.Get<MitivoUserAuth>(1)
    };

    Container.Register(MitivoApiAuthSession);
}

I do inherit correctly:

public class MitivoApiAuthSession : AuthUserSession { ... }

as I’m registering in the Container shouldn’t it pick up automagically?

Ideally you shouldn’t register your User Session in the container, but we do allow it for HostContext.TestMode like within the context of a BasicAppHost as it looks like this test is in, so not sure why it’s not picking it up as it’s the first thing that’s checked.

But another way to inject your session is by populating it in IRequest.Items, e.g:

var req = new MockHttpRequest();
req.Items[Keywords.Session] = new MitivoApiAuthSession();
var service = new MyService { Request = req };
1 Like

It’s always a privilege to learn a bit more.

Thank you so much for the help, it’s all working now :smile:

I’m sure this post will be helpful to some developers!

1 Like

It turns out this was an issue in latest release fixed with commit and available from v4.0.61 on MyGet.

But It should work in the current release if you register it against IAuthSession, e.g:

container.Register<IAuthSession>(c => new MitivoApiAuthSession { ... });
1 Like