Using ServiceStack's Funq to LazyResolve dependencies - servicestack

We are using ServiceStack in a web hosted API service, and have done so for awhile now. The execution path for any request follows the pattern:
Request comes in:
--> Service (handles request, utilizes IManager injected via constructor)
--> IManager (performs business logic, utilizes IRepository/ies that are injected via constructor)
--> IRepository/ies (SQL Server, NoSQL, utilizes connection factory/ies injected by constructor)
Now that we are entertaining another client, some of these requests need to follow slightly different business logic, and potentially utilize a different repo strategy. However, the API will remain consistent. To this end, I am extracting client specific logic (the concrete IManager and IRepository implementations above) to separate assemblies. I've written a component that inspects the current request context, identifying the client this request is for, which then uses reflection and the Activator to instantiate an instance of the specific implementation I want to execute for any given request.
However, because of this, I can't just register implementations of IManager and IRepository in the container at startup - this needs to be resolved dynamically per request. I'd like to do some type of LazyResolve, but I can't find any solid example of how this is done to get me started here.
Am I thinking crazy here? My API is essentially just that with this - the custom logic that occurs is isolated to client specific assemblies that are called at runtime. This all makes perfect sense to me in theory, but in practice it's proving a challenge. Thoughts? Ideas?

If you only want to resolve adhoc dependencies at runtimes you can just resolve them from the IOC as needed in your Service with:
base.TryResolve<T>();
In any Filter from IRequest with:
req.TryResolve<T>();
Or externally outside ServiceStack with:
HostContext.TryResolve<T>();

Related

Do Azure Functions have a request pipeline of some kind?

I would like to add some common authentication code to a collection of HttpTrigger Azure Functions (v3), which I'm using as an API. I know about the service-side auth associated with AuthorizationLevel.Function, but that won't work for me. The type of auth I need to do is relatively simple: just check a specific HTTP header for a specific value.
In ASP.NET, this kind of thing can be done in an HttpModule. Do Azure Functions have a similar request pipeline of some kind?
As far as I can tell from the documentation, it looks like new Function instances can call Startup.Configure() before calling the target method, if the project is appropriately configured. However, those calls are intended to support Dependency Injection, and don't have access to the HttpRequest object.
Obviously, I could just put an isAuthorized(request) call at the beginning of each API entry point, but that feels klunky, repetitive, and potentially error-prone. Is there a better way?

Apply IHasRequestFilter to Plugin registered service dynamically

I have a set of Services that I want to use in various ServiceStack projects (okay, two) so I have created a ServiceStack Plugin that registers them.
However I want to allow users to determine their own method of securing access to these services.
Currently I have an IHasRequestFilter in one my projects that can determine which services a user should be able to access. I do not want a reference to this in the Plugin project, so I want to add this dynamically after the fact.
I want to somehow get a reference to the Service Definition in AppHost to add this IHasRequestFilter to the pipeline for a specific set of services.
Ideally I should be able to do something like this:
new CustomPlugin(new CustomPluginParams {
RestrictTo = CustomRestrictions,
RequestFilters = [],
ResponseFilters = []
});
This should use those properties to configure their services without having a previous typed reference.
Edit:
Investigating further it appears that the IHasRequestFilter and IHasResponseFilters are only parsed once, in the ServiceExec<TService> class. I could get round this by creating my Services with a Proxy which adds the attribute I require to the MemberInfo of the operations, however I don't regard that as a clean approach.
Does anyone have recommendation?
In ServiceStack all configuration should happen within AppHost's Configure() method and remain immutable thereafter.
Lifecycle Events
To help with LifeCycle events there are IPreInitPlugin and IPostInitPlugin Plugin Interfaces which your Plugins can implement so they will get called back before and after all plugins are registered.
There's also an IAppHost.AfterInitCallbacks plugins can use to get called back after the entire AppHost has finished initialiazing.
Typed Request/Response Filters
Attributes are typically statically defined on Services, to dynamically add logic that apply to specific Request/Responses you can use a typed Request/Response filter.
The nice thing about ServiceStack Filters is that they share the same API (IRequest, IResponse, object) which makes them easily composable, e.g:
RegisterTypedRequestFilter<CustomRequest>(new RequestAttributeFilter().Execute);
Dynamically adding Attribute filters
As all ServiceStack libraries use ServiceStack.Text's Reflection API's you're able to extend ServiceStack's attribute-based code-first API dynamically by adding attributes to types or properties at runtime, e.g:
typeof(CustomRequest)
.AddAttributes(new RuntimeAttributeRequestFilter());
This can be done for most of ServiceStack's code-first API's inc. Request/Response Filters.
Route attributes and Action Filters
There is sometimes an issue for Services Route attributes and Action filters that already pre-configured and autowired before the AppHost's Configure() is called.
One solution is to add them in the AppHost constructor (or by overriding AppHost.OnBeforeInit) so they're added before the Services are configured. Otherwise you can reset the action filter caches by calling the AppHost's ServiceController.ResetServiceExecCachesIfNeeded().

Is there a way to link a specific method to a Route in ServiceStack?

The Problem
I'm aware of the basic way to create a route/endpoint in ServiceStack using methods with names like "Get", "Post", "Any", etc inside a service but in the particular case that I'm trying to work with I have an existing service (which I can make an IService via inheritance) that can not be retrofitted w/ServiceStack attributes and currently uses DTOs for the requests and responses.
This service contains many functions that I do not want to manually mask (as this is a pass-through layer) but otherwise already conform to ServiceStack's requirements. What I'm wondering is if there's a way to manually create these routes in a way that would work like I've mocked up here. My existing functions and DTOs already contain the information I would need to define the routes so if this approach is possible it would only require me to enumerate them at initialization time as opposed to generating the services layer manually.
I noticed there is an extension method on Routes.Add that takes an Expression of type Expression> but I was not able to get that working because I believe the underlying code makes assumptions about the type of Expression generated (LambdaExpression vs MemberExpression or something like that). I also may be barking up the wrong tree if that's not the intended purpose of that function but I can not find documentation anywhere on how that variant is supposed to work.
Why?
I'm not sure this is necessary but to shed some light on why I want to do this as opposed to retrofitting my existing layers: The current code is also used outside of a web service context and is consumed by other code internally. Retrofitting ServiceStack in to this layer would make every place that consumes it require ServiceStack's assemblies and be aware of the web service which is a concern I want separated from the lower code. We were previously using MVC/WCF to accomplish this goal but we want some of the features available from ServiceStack.
the current architecture looks like this:
data -> DAL -> discrete business logic -> composition -> web service
Hopefully that makes enough sense and I'm not being obtuse. If you would like any more details about what I want to do or why I'll try to update this post as soon as possible.
Thanks!
You might use the fallback route in order to provide your own routing mechanism.
Then you get the request.Path property and route using your own mapping of path:Function which can be stored in a simple dictionary.
Anyway, if you go this path I don't see much benefit in using servicestack. It seems you just need an http handler that routes requests to existing services.

ServiceStack.Examples\src\ServiceStack.Examples is not RESTful?

I'm struggling to see how this is RESTful. I'm referring to the downloaded GitHub ServiceStack.Examples\src\ServiceStack.Examples\ServiceStack.Examples.sln. I do not see anything restful about this, there is no RESTful routes here at all and the method names are all verbs but they're all like GEtThis, etc. I don't see any Http verb attributes, nothing here.
Can someone explain what this is here becuase I feel like it doesn't even belong in the ServiceStack examples...??
Nobody said that example was supposed to be RESTful.
ServiceStack is a general services framework that lets you implement SOAP, MQ or REST+Web/HTML services with the same service.
The example your looking at is one of the first examples ever created for ServiceStack which makes use the Old API. You can compare and contrast it with the New API here. Since the example implements IService<T> it's not a REST service, since every HTTP Verb will invoke the same implementation above. To provide different implementations for each verb with the Old API you would need to inherit RestServiceBase<T> instead, or preferably use the New API.
If you want to consume this service via SOAP or MQ hosts than you need to ensure its accessible via POST by either maintaining single operation per Request DTO like this or by using a method named either Post() or Any() in the New API.

Calling a ServiceStack service from Razor

A bit of an edge case here:
I need to call a servicestack service from razor (same website)
Right now I'm doing
CheckIfConfiguredResponse aResponse= new JsonServiceClient("http:\\localhost:2000").Get<CheckIfConfiguredResponse>("/CheckIfConfigured");
Is that the proper way to go about doing it? Or is there better?
Also, How do I eliminate having to specify the web address manually and have it automatically populate the host (since it's the same web site)
Thanks in advance,
Will.
You never want to make a HTTP call back to yourself just to call a ServiceStack service.
Unlike other frameworks, Services in ServiceStack are simply auto-wired C# types which you can access from the IOC like every other registered IOC dependency. i.e. Inside a Razor View you can simply resolve it and call it directly from the IOC with:
var response = base.Get<CheckIfConfiguredService>().Get(new CheckIfConfigured());
This resolves and calls the service like a normal auto-wired C# dependency, but doesn't inject the current request context. If your service does need it, you can instead use AppHostBase.ResolveService which does, e.g:
var response = AppHostBase
.ResolveService<CheckIfConfiguredService>(HttpContext.Current)
.Get(new CheckIfConfigured());

Resources