How to inject HttpRequestBase and HttpContextBase in Funq (while using ServiceStack) - servicestack

I have been happily using AutoFaq for a couple of years and take advantage of its ability to easily inject HttpRequestBase and HttpContextBase in the MVC pipeline. This makes mocking and decoupling a lot easier.
I am in the process of changing my data layer to ServiceStack and as part of wiring the default Funq DI mechanism to my different layers I can't figure out how to inject HttpRequestBase and HttpContextBase.
Is there a way to do this? I am looking for the container.Register() analog inside of AppHost.Configure(Func.Container container).
Thanks

ServiceStack doesn't allow registering runtime dependencies with its IOC, although as ServiceStack Services and Request pipeline only binds to the IRequest interface which can just inject a mocked IRequest directly on the service when its required, e.g:
var service = new MyService {
Request = new MockHttpRequest()
};
var response = service.Get(new MyRequest { Id = 1 });
The Testing wiki shows other ways of testing ServiceStack services.

ServiceStack has it's own abstraction of the HttpContext and Request/Response. In v3.x, these are IRequestContext, IHttpRequest, IHttpResponse. This is to be implementation-independent of ASP.NET (console or Mono). It is recommended you use the abstractions instead of trying to use the underlying ASP.NET objects.
In your Service code, you may access them this way:
var httpReq = base.RequestContext.Get<IHttpRequest>();
var httpResp = base.RequestContext.Get<IHttpResponse>();
If you really need the real ASP.NET HttpContext, apparently you should be able to access it at IRequest.OriginalRequest. But if you are trying it the ServiceStack way, "don't do that".
More explanation of the Funq usage in v3 is here:
https://github.com/ServiceStackV3/ServiceStackV3/wiki/The-IoC-container

Related

ServiceStack: Generate OpenAPI spec without creating the Service implementation classes

ServiceStack has support for OpenAPI and can generate an OpenAPI spec. However, for APIs/endpoints to be generated in the spec, it is not enough to specify the API details using the Route attributes as described here, you also need to create the Service classes that (eventually) implement the functionality.
Is there a way to make the OpenAPI specification include everything without having to create the Service classes that go with them?
The reason is that sometimes you just want to work on the specification, not implementation (even though you can just skip implementation details and throw a NotImplementedException), and creating those Service classes just to get the spec to show is annoying.
If it doesn't have an implementation it's not a Service and therefore wont have any of ServiceStack's metadata or features available for it.
If you want to skip their implementation you can just create stub implementations for them, e.g:
public class MyServices : Service
{
public object Any(MyRequest1 request) => null;
public object Any(MyRequest2 request) => null;
public object Any(MyRequest3 request) => null;
}

.NET 6.0 ServiceStack 6.1.1 JsonServiceClient doesn't use /json/reply

I have two application one is an API and is using SS v5.10.4 the other one is a service that was using SS v5.8.0 and was upgraded to v6.1.1
The service is referencing the API's DTOs using the ServiceStackVS plugin which creates a single *.dto file. Some of the DTOs in the API have custom routes others don't. Prior to upgrading the service to SS v.6.1.1 the calls using the DTOs without custom routes were going to /json/reply/{requestDTO} and the ones with custom routes were going to /{Route}. After the upgrade all calls are now going to /{requestDTO}. Any idea why that is and is there an easy way to default the JsonServiceClient to use the /json/reply/{requestDTO} if there isn't a custom route defined in the {myAPI}.dtos file for the specific DTOs ?
So seems like it's working as expected if I set the baseUri in the constructor of the JsonServiceClient instead of setting the BaseUri property.
Doesn't work:
_client = new JsonServiceClient
{
BaseUri = _configuration.ClientUri,
Timeout = TimeSpan.FromMinutes(_configuration.RequestTimeOut)
};
Works:
_client= new JsonServiceClient(_configuration.ClientUri)
{
Timeout = TimeSpan.FromMinutes(_configuration.RequestTimeOut)
};

Servicestack Multitenancy dynamic plugins

We are moving from an on premise-like application to a multi tenant cloud application.
for my web application we made a very simple interface based on IPlugin, to create a plugin architecture. (customers can have/install different plugins)
public interface IWebPlugin : IPlugin
{
string ContentBaseUrl { set; get; }
}
We have some plugins that would normally be loaded in on startup. Now i'm migrating the code to load at the beginning of a request (the Register function is called on request start), and scope everything inside this request.
It's not ideal but it would bring the least impact on the plugin system for now.
I could scope the Container by making an AppHost child container which would stick to the request:
Container IHasContainer.Container
{
get
{
if (HasStarted)
return ChildContainer;
return base.Container;
}
}
public Container ChildContainer
{
get { return HttpContext.Current.Items.GetOrAdd<Container>("ChildContainer", c => Container.CreateChildContainer()); }
}
problem case
Now im trying to make plugins work that actually add API services.
appHost.Routes.Add<GetTranslations>("/Localizations/translations", ApplyTo.Get);
But this service is unreachable (and not visible in metadata). How do i make it reachable?
I see you execute the following in ServiceController AfterInit. Re-executing this still wouldnt make it work.
//Copied from servicestack repo
public void AfterInit()
{
//Register any routes configured on Metadata.Routes
foreach (var restPath in appHost.RestPaths)
{
RegisterRestPath(restPath);
//Auto add Route Attributes so they're available in T.ToUrl() extension methods
restPath.RequestType
.AddAttributes(new RouteAttribute(restPath.Path, restPath.AllowedVerbs)
{
Priority = restPath.Priority,
Summary = restPath.Summary,
Notes = restPath.Notes,
});
}
//Sync the RestPaths collections
appHost.RestPaths.Clear();
appHost.RestPaths.AddRange(RestPathMap.Values.SelectMany(x => x));
appHost.Metadata.AfterInit();
}
solution directions
Is there a way i could override the route finding? like extending RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType);
Or could i restart the path compilation/caching? (would be enough for now that the service would be reachable tenant wide )
All configuration in ServiceStack should be contained within AppHost.Configure() and remain immutable thereafter. It's not ThreadSafe to modify ServiceStack's Static Configuration at runtime like trying to modify registered routes or Service Metadata which needs to be registered once at StartUp in AppHost.Configure().
It looks as though you'll need to re-architect your solution so all Routes are registered on Startup. If it helps Plugins can implement IPreInitPlugin and IPostInitPlugin interfaces to execute custom logic before and after Plugins are registered. They can also register a appHost.AfterInitCallbacks to register custom logic after ServiceStack's AppHost has been initialized.
Not sure if it's applicable but at runtime you can "hi-jack Requests" in ServiceStack by registering a RawHttpHandler or a PreRequestFilter, e.g:
appHost.RawHttpHandlers.Add(httpReq =>
MyShouldHandleThisRoute(httpReq.PathInfo)
? new CustomActionHandler((req, res) => {
//Handle Route
});
: null);
Simple answer seems to be, no. The framework wasn't build to be a run-time plugable system.
You will have to make this architecture yourself on top of ServiceStack.
Routing solution
To make it route to these run-time loaded services/routes it is needed to make your own implementation.
The ServiceStack.HttpHandlerFactory checks if a route exist (one that is registered on init). so here is where you will have to start extending. The method GetHandlerForPathInfo checks if it can find the (service)route and otherwise return a NotFoundHandler or StaticFileHandler.
My solution consists of the following code:
string contentType;
var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType);
//Added part
if (restPath == null)
restPath = AppHost.Instance.FindPluginServiceForRoute(httpMethod, pathInfo);
//End added part
if (restPath != null)
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.GetOperationName(), ResponseContentType = contentType };
technically speaking IAppHost.IServiceRoutes should be the one doing the routing. Probably in the future this will be extensible.
Resolving services
The second problem is resolving the services. After the route has been found and the right Message/Dto Type has been resolved. The IAppHost.ServiceController will attempt to find the right service and make it execute the message.
This class also has init functions which are called on startup to reflect all the services in servicestack. I didn't found a work around yet, but ill by working on it to make it possible in ServiceStack coming weeks.
Current version on nuget its not possible to make it work. I added some extensibility in servicestack to make it +- possible.
Ioc Solution out of the box
For ioc ServiceStack.Funq gives us a solution. Funq allows making child containers where you can register your ioc on. On resolve a child container will, if it can't resolve the interface, ask its parent to resolve it.
Container.CreateChildContainer()

ServiceStack message queue handling and Profiler

I'm currently trying out the persistent mini profiler feature of ServiceStack and I'm currently having trouble registering profile information for my Redis Message Queue handlers.
A bit more background:
I have some regular REST api handlers which takes in a request, defers some updates of account information and replies OK back to the caller. These messages are posted to a Redis server, using the ServiceStack Redis MQ pattern. Therefore, the Redis message handling is registered as:
var redisFactory = new PooledRedisClientManager(redisClients);
var mqHost = new RedisMqServer(redisFactory, retryCount: 2);
var defaultThreadCount = 4;
mqHost.RegisterHandler<SomeDto>(m => this.ServiceController.ExecuteMessage(m), noOfThreads:defaultThreadCount);
mqHost.RegisterHandler<SomeOtherDto>(m => this.ServiceController.ExecuteMessage(m), noOfThreads:defaultThreadCount);
mqHost.Start();
And my messages are being handled properly too.
In a custom ServiceRunner I've enabled profiling of all requests in the BeforeEachRequest and added a custom Profiler step like this:
public override void BeforeEachRequest(IRequest requestContext, T request)
{
Profiler.Start();
using (Profiler.StepStatic("Executing handler"))
{
base.BeforeEachRequest(requestContext, request);
}
}
All my HTTP REST requests are making it to the SQL tables, but none of the MQ handler calls are registered. And I'm 100% confident that the handlers are indeed being executed, since the result of that execution is stored in a MongoDB collection.
Anything I'm missing?
-- EDIT --
I forgot to mention that this project is indeed hosted via an ASP.NET application. The AppHost is initialized in Global.asax App_Start - I just found it more convenient to have "before request" handing in a custom service runner rather than the ASP.NET Begin_Request handler.
I have a similar problem with a self hosted server. The problem is that the profiler uses HttpContext.Current to store the profiling results. If there is no valid context it does not know which profiling 'session' to add the results to.
It is possible to implement your own ProfilingProvider by setting Profile.Settings.ProfilingProvider, but, unless I am missing something, it will be tricky (if not impossible) to implement this properly in an Async environment with the current IProfilerProvider interface.
I wrote a very simple and naive provider which you can use for profiling. This will not pick up any of the steps that ServiceStack already adds by default, but it might still be useful for your own debugging.
Example use:
Profiler.Settings.ProfilerProvider = RequestProfilerProvider.Instance;
PreRequestFilters.Add((req, res) => RequestProfiler.Start(req));
GlobalRequestFilters.Add((req, res, dto) => {
var profiler = RequestProfiler.GetProfiler(req);
using (profiler.Step("Very slow step")) {
Thread.Sleep(1000);
}
});
GlobalResponseFilters.Add((req, res, dto) => RequestProfiler.Stop(req));

Can ACS Service Namespace creation be automated?

First, let me state my real problem: I've got code that makes calls to the ACS Management service, and I'd like my integration tests to be able to be run concurrently without each test run clobbering the others. That is, since multiple people / build servers might end up running these tests concurrently, if they're all using the same ACS service namespace, concurrency issues arise.
My thinking is the simplest means of achieving this would be to generate new, unique ACS service namespaces for each test runner -- but as far as I can tell, there's no automated way of creating new service namespaces (or management client keys). Am I wrong? Is there another way of going about this?
An automated method of creating new service namespaces would be extraordinarily helpful.
You are correct. That's not possible today. Maybe you can describe your scenario in more detail and there might be some alternative solutions to avoid having to recreate the namespace?
Technically it should be possible, since the Management Portal is a Silverlight application accessing a WCF RIA Service.
If you dig deep enough you'll find some useful information:
This is the Silverlight XAP for the management of Windows Azure AppFabric: https://appfabricportal.windows.azure.com/ClientBin/Microsoft.AppFabric.WebConsole.4.1.3.xap
This is the service being used when listing/creating/... namespaces etc..: https://appfabricportal.windows.azure.com/Services/Microsoft-AppFabric-Web-Services-AppFabricDomainService.svc?wsdl
And this is a piece of the DomainContext:
public sealed class AppFabricDomainContext : DomainContext
{
public AppFabricDomainContext(Uri serviceUri)
: this((DomainClient) new WebDomainClient<AppFabricDomainContext.IAppFabricDomainServiceContract>(serviceUri, true))
{
}
...
public InvokeOperation CreateServiceNamespace(IEnumerable<string> serviceNames, string parentProjectKey, string serviceNamespace, IEnumerable<string> packageKeys, string regionKey, Action<InvokeOperation> callback, object userState)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("serviceNames", (object) serviceNames);
dictionary.Add("parentProjectKey", (object) parentProjectKey);
dictionary.Add("serviceNamespace", (object) serviceNamespace);
dictionary.Add("packageKeys", (object) packageKeys);
dictionary.Add("regionKey", (object) regionKey);
this.ValidateMethod("CreateServiceNamespace", (IDictionary<string, object>) dictionary);
return this.InvokeOperation("CreateServiceNamespace", typeof (void), (IDictionary<string, object>) dictionary, true, callback, userState);
}
}
Finding this info was the easy part, getting it to work... that's something else. Take the authentication part for example, you'll need to authenticate with Windows Live and use those credentials when calling the WCF RIA Service.
Good luck!

Resources