5

我正在努力寻找将UserAuthSession对象的当前实例(源自 ServiceStack 的AuthUserSession)注入我的数据访问存储库的正确方法,以便它们在插入/更新/删除操作时自动更新更改跟踪字段。

如果我在我的服务代码中更新存储库,那将是一件轻而易举的事,我会这样做:

var repo = new MyRepository(SessionAs<UserAuthSession>());

但是,我的存储库是自动连接(注入)到服务中的,因此UserAuthSession必须从为存储库注册到 IOC 容器而定义的 lambda 中的某个位置获取,例如:

public class AppHost : AppHostBase
{
    public override void Configure(Container container)
    {
        container.Register<ICacheClient>(new MemoryCacheClient());
        container.Register<IRepository>(c =>
        {
            return new MyRepository(**?????**);  <-- resolve and pass UserAuthSession
        }
    }
}

现在,查看Service该类的 ServiceStack 代码:

    private object userSession;
    protected virtual TUserSession SessionAs<TUserSession>()
    {
        if (userSession == null)
        {
            userSession = TryResolve<TUserSession>(); //Easier to mock
            if (userSession == null)
                userSession = Cache.SessionAs<TUserSession>(Request, Response);
        }
        return (TUserSession)userSession;
    }

Request我可以看到它根据当前and查找缓存的会话Response,但是这些在 lambda 中对我不可用。

解决方案是什么?还是我从一个完全错误的角度来解决问题?

4

1 回答 1

6

在另一个 StackOverflow 帖子中找到了答案,该帖子将根据请求构建的会话存储ItemsServiceStack.Common.HostContext. .

AppHost.Configure()现在有以下代码:

// Add a request filter storing the current session in HostContext to be
// accessible from anywhere within the scope of the current request.
RequestFilters.Add((httpReq, httpRes, requestDTO) =>
{
    var session = httpReq.GetSession();
    HostContext.Instance.Items.Add(Constants.UserSessionKey, session);
});

// Make UserAuthSession resolvable from HostContext.Instance.Items.
container.Register<UserAuthSession>(c =>
{
    return HostContext.Instance.Items[Constants.UserSessionKey] as UserAuthSession;
});

// Wire up the repository.
container.Register<IRepository>(c => 
{ 
    return new MyRepository(c.Resolve<UserAuthSession>()); 
});
于 2013-07-11T20:56:11.833 回答