RegisterTypedRequestFilter<IForEnvironment>((req, res, requestDto) =>
{
Guid.TryParse(req.Headers["User"], out Guid user);
Guid.TryParse(req.Headers["Tenant"], out Guid tenant);
requestDto.Tenant = tenant;
requestDto.User = user;
req.Items[Keywords.DbInfo] = new ConnectionInfo() { ConnectionString = GetEnvironmentConnString(dbFactory, requestDto.Environment) };
using (var db = dbFactory.Open())
{
db.Insert(new Event()
{
Name = requestDto.GetType().Name,
Tenant = tenant,
Environment = requestDto.Environment,
User = user
});
}
});
I did this so I don’t have to put this code in every service method. However, the db.Insert part is what I’m wondering if there is a better way. I was trying to figure out how to get the IDbConnection (Service.Db) of the IRequest because I figure this is a bit cleaner:
RegisterTypedRequestFilter<IForEnvironment>((req, res, requestDto) =>
{
Guid.TryParse(req.Headers["User"], out Guid user);
Guid.TryParse(req.Headers["Tenant"], out Guid tenant);
requestDto.Tenant = tenant;
requestDto.User = user;
req.Items[Keywords.DbInfo] = new ConnectionInfo() { ConnectionString = GetEnvironmentConnString(dbFactory, requestDto.Environment) };
Db.Insert(new Event()
{
Name = requestDto.GetType().Name,
Tenant = tenant,
Environment = requestDto.Environment,
User = user
});
});
But Service.Db doesn’t seem to be available from here. Any advice on how to do this a better way would be appreciated.
The request filters are executed before the Service is created to execute the Service. Your Request Filter is just opening the default connection directly from the dbFactory.
Here’s Service implementation that resolves its Db:
Related question: Is there some built in ServiceStack way of enabling a global event logger to log all service requests (by default) along with request parameters, authenticated user, etc to something like Serilog?
Ya, I saw that in the source code, but I’m definitely in DebugMode. I’m using self hosting Kestrel, not IIS Express, so maybe that’s it? The console window for self host even says:
Hosting environment: Development
So, since RequestLogService is enforcing the roles check, I’m assuming that it thinks:
if (!HostContext.DebugMode)
{
RequiredRoleAttribute.AssertRequiredRoles(Request, RequestLogger.RequiredRoles);
}
Is True.
In any event, your suggestion to add an empty array to RequiredRoles did the trick.