#RepositoryEventHandler only invoked via HTTP - why? - spring-data-rest

when I use a #RepositoryEventHandler then its methods are only invoked when the call into the repository comes in via HTTP.
Any reason why? OK, it is called Spring Data REST, but wouldn't it be VERY useful to invoke the handler too, when I call my Repo directly, not via HTTP?
Any way to invoke the handler when called directly (some magic AOP-stuff)?
Thank you

The reason for that is that the different persistence mechanisms covered by the different Spring Data modules already ship with event mechanisms. Depending on the one you use you now get a different mechanism to use.
Unfortunately this can't be unified as e.g. with JPA not all persistence operations need to go through the repository in the first place, as JPA automatically flushes all changes that were made to an attached instance on EntityManager flush. In this case even AOP on the repository instance doesn't help.
So you're basically left with two choices:
The events exposed by Spring Data REST for all repositories (as we basically don't make use of the automatic change tracking in JPA).
The store specific event mechanisms that will make sure that the persistence mechanism exposes events as documented.

I don't know if the solution I put below from other stackoverflow questions would seen as acceptable by #Olivier-drotbohm, but from:
SpringDataRest #RepositoryEventHandler not running when Controller is added
and
#RepositoryEventHandler events stop with #RepositoryRestController
you could inject/autowire the "ApplicationEventPublisher" and fire the BeforeCreateEvent/AfterCreateEvent manually to trigger the RepositoryEventHandler.
This is not a perfect solution, but I hope it is good enough for you (and we tested it: it works).

Related

Using selection strategies with a cache in Curator

The page on Service Discovery using apache curator (https://github.com/Netflix/curator/wiki/Service-Discovery) introduces the following concepts:
The main abstraction class is ServiceProvider. It encapsulates the discovery service for a particular named service along with a provider strategy. A provider strategy is a scheme for selecting one instance from a set of instances for a given service. There are three bundled strategies: Round Robin, Random and Sticky (always selects the same one). ServiceProviders are allocated by using a ServiceProviderBuilder.
Each of the above query methods calls ZooKeeper directly. If you need more than occasional querying of services you can use the ServiceCache. It caches in memory the list of instances for a particular service. It uses a Watcher to keep the list up to date. You allocate a ServiceCache via the builder returned by ServiceDiscovery.serviceCacheBuilder().
I can see how to use the Provider strategies with a ServiceProviderBuilder, but there's no equivalent method on the ServiceCacheBuilder, and the only relevant method available on the ServiceCache class itself is getInstances(), which gets all instances.
How can I use a provider strategy with a ServiceCache?
#simonalexander2005 I was just looking in the code and it turns out that ServiceProvider internally already uses a serviceCacheBuilder. TBH - I've either forgotten about this or it got put in by another committer - I'm not sure. Anyway, I'm very sorry about the runaround here. Also, the documentation must be updated to reflect this - I'll open an issue for this today. I'm sure this be maddening to you, again sorry for this. The good news, though, is that with ServiceProvider you automatically get caching.
Frankly, the docs on this are really bad. It would be fantastic if someone could give a pull request with better docs...
Notice that ServiceCache implements InstanceProvider. Also notice that ProviderStrategy.getInstance() has as its argument InstanceProvider. Therefore, you can pass a ServiceCache instance to whichever ProviderStrategy you want to use.
I hope this helps.

Access Service Provider Context in HystrixCommand's RunFallbackAsync

I am working to add the Hystrix CircuitBreaker pattern to an existing ASP.NET Core microservice, using Steeltoe CircuitBreaker, while maintaining the existing logging functionality with minimal refactoring (or as little as I can hope for).
Currently, an incoming HTTP request goes through the following layers:
Controller -> Service -> DerivedProvider -> AbstractProvider (and out to downstream service)
with Hystrix, I would like it to be:
Controller -> Service -> HystrixCommand<> -> DerviedProvider (via HystrixCommand's ExecuteAsync) -> AbstractProvider
Lots of context is stored in the providers, which is passed down through the layers via constructors, and logging is then happening in the AbstractProvider using that context, regardless of the outgoing call's result. The AbstractProvider also supports a fair amount of custom logic, such as optional pre and post execution callbacks. The post callback is invoked when a non-success response message is returned. Needless to say, changing the layers drastically doesn't appear easy to me, with my current understanding.
After reviewing the Hystrix documentation and Steeltoe CircuitBreaker documentation I am unclear if I can maintain, and access, the provider and its context within the HystrixCommand<>.RunFallbackAsync().
Perhaps the answer might relate to the lifecycle hooks you can override? Like onFallbackStart(HystrixInvokable commandInstance?
Ultimately, the goal is simply to make sure that any existing callback/logging functionality is not lost by wrapping these existing providers in a HystrixCommand. I am failing to understand how the HystrixCommand manages the providers and its context, and when/where you do or do not have access to them. Any suggestions or direction you can offer would be very much appreciated! Cheers!
Hystrix commands can be added to the service container or can be "new'd" (i.e. new MyHystrixCommand(...) whichever makes the most sense for you situation.
Remember that Hystrix commands can not be reused .. i.e. once you create and execute the command you must not try and reuse it.
Clearly if you are new'ng the HystrixCommand then you can define whatever arguments you want in the constructor and supply it with the right arguments (i.e. state) it needs to execute.
If you are injecting it into a controller or another service.. then before you use it... you can initialize it with whatever state you want using properties and then execute it.

Change implementation of ninject dependency after singleton instantiation

So, I have a viewmodel class in a xamarin project that I inject some dependencies into via ninject binding on app start. One of these is an IDialogService.
When my MainPage in my application changes it raises a property changed event and I rebind the implementation of the dialog service since it is tied to the MainPage.
If my viewmodel has already been created with lets say DialogServiceA and then when MainPage changes we rebind to DialogServiceB, will my viewmodel be using service A or B? I think it is using A and therefore does not display in the UI because it is tied to a MainPage that no longer exists.
So, if this is the case how can I dynamically change my dialog service but then update classes that have already been instantiated without changing everything to get the current dialog service from the container every time its used (therefore not injecting it at all really, and doing more of a servicelocator)
Also, if this approach is completely wrong, set me straight.
You're right. Re-configuration of the container does not affect already instanciated objects.
If you want to change dependencies without re-instanciating the dependent (parent ViewModel) there's a few possibilities for you:
use a factory to instanciate the service every time. Implement an Abstract Factory (Site by Mark Seeman) or use Ninject.Extensions.Factory to do so
instead of injecting a service directly, inject an adapter. The adapter then redirects the request to the currently appropriate service. To do so, either all service can be injected into the adapter, or you can use a factory as with the possibility above.
instead of inject a service directly, inject a proxy. The proxy is quite similar to the adapter, but instead of coding every method / property redirection specifically, you code a generic redirect by an interceptor. Here's a tutorial on castle dynamic proxy
At the end of the day, however, i believe you'll also need a way to manage when to change the service / which it should be. There's probably a design alternative which doesn't rely on exchanging objects in such a manner.. which would make it an easier (and thus better?) design.
Edit: i just saw that you also tagged the question as xamarin-forms. In that case it most likely won't be an option to use either a dynamic proxy nor ninject.extensions.factory (it relies on dynamic proxies, too). Why? dynamic proxy / IL emitting is not supported on all platforms, AFAIR specifically on Apple devices this can't be done.

NServiceBus Endpoint Routing Injection

I am trying to inject my own IRouteMessagesToEndpoints in NServiceBus with structure map as I need to redirect various messages to different endpoints depending on some business logic (not via namespace/assembly/type). This would allow it to fire using bus.Send(); and be configured to our requirements. I thought this was possible, but I can't seem to get it to work. I have tried using the Configure.Component() and ObjectFactory.Configure() for the injection, and both run without any exception, but when I debug my implementation of the interface the breakpoint does not hit.
My question is, can it be done this way (there's nothing on the internet that covers this)? I notice that the EndPointRouter in the GatewayReceiver has a setter, but I cannot work out how to access the property.
Unfortunately, even though IRouteMessagesToEndpoints is a public interface at the moment is not possible to replace the default implementation, sorry!
Please raise an issue about it in https://github.com/Particular/NServiceBus.Gateway/issues/new so we can discuss it better.

Passing client context using Unity in WCF service application

I have a WCF service application (actually, it uses WCF Web API preview 5) that intercepts each request and extracts several header values passed from the client. The idea is that the 'interceptor' will extract these values and setup a ClientContext object that is then globally available within the application for the duration of the request. The server is stateless, so the context is per-call.
My problem is that the application uses IoC (Unity) for dependency injection so there is no use of singleton's, etc. Any class that needs to use the context receives it via DI.
So, how do I 'dynamically' create a new context object for each request and make sure that it is used by the container for the duration of that request? I also need to be sure that it is completely thread-safe in that each request is truly using the correct instance.
UPDATE
So I realize as I look into the suggestions below that part of my problem is encapsulation. The idea is that the interface used for the context (IClientContext) contains only read-only properties so that the rest of the application code doesn't have the ability to make changes. (And in a team development environment, if the code allows it, someone will inevitably do it.)
As a result, in my message handler that intercepts the request, I can get an instance of the type implementing the interface from the container but I can't make use of it. I still want to only expose a read-only interface to all other code but need a way to set the property values. Any ideas?
I'm considering implementing two interfaces, one that provides read-only access and one that allows me to initialize the instance. Or casting the resolved object to a type that allows me to set the values. Unfortunately, this isn't fool-proof either but unless someone has a better idea, it might be the best I can do.
Read Andrew Oakley's Blog on WCF specific lifetime managers. He creates a UnityOperationContextLifetimeManager:
we came up with the idea to build a Unity lifetime manager tied to
WCF's OperationContext. That way, our container objects would live
only for the lifetime of the request...
Configure your context class with that lifetime manager and then just resolve it. It should give you an "operation singleton".
Sounds like you need a Unity LifetimeManager. See this SO question or this MSDN article.