DryIOC, MediatR - DecoratorWith condition evaluated multiple times with keyed parameter - dryioc

This question is yet another follow-up to a previous question regarding the setup of DryIOC with MediatR and decorators: DryIOC and MediatR: Injection using InResolutionScopeOf for both IAsyncNotificationHandler and IAsyncRequestHandler
In this example, the setup is similar to the one of my previous question, we have requests (IAsyncRequestHandler) and notifications (IAsyncNotificationHandler), and the notifications are being fired from the requests, and both have a dependency on a DbContext with needs to be injected per resolution scope.
What I'm doing now is decorating IAsyncRequestHandler and i'm passing a dependency of type IActionHandler to the decorator using a key. I'm registering the dependency like this:
c.Register<IActionHandler, SomeActionHandler>(serviceKey: "key1");
And then, passing the parameter to the decorator like this:
c.Register(typeof(IAsyncRequestHandler<,>), typeof(Decorator<,>),
made: Parameters.Of.Type<IActionHandler>(serviceKey: "key1"),
setup: DryIoc.Setup.Decorator);
Set up like this, the notification is fired from the request handler successfully. However if I add more decorators and change the setup parameter of the decorator to DecoratorWith and specify a condition (even if it simply returns true), the notification isn't fired from the request handler because the DbContext isn't injected successfully into the IAsyncNotificationHandler.
Here is a fiddle which shows the problem https://dotnetfiddle.net/ob0nfA
When debugging, i found out that the condition in DecoratorWith of the first decorator is called twice for the same service type, when there are two registrations. I'm not sure if this is intended or not, however I believe that might be related to the problem, because if I simply return true, then multiple decorators will be registered for the same handler, when there should only be one.
I know I would be able to register the decorator dependencies using Made instead, but in this specific instance keyed registration seems better for my intended setup.
So I'd like to know if there's something I'm missing, or in the case that DecoratorWith works as intended by being called more than once for the same service type, I'd like to know if there is a way that I can distinguish the calls, so that i can register the decorator properly only once.
Or maybe the problem lies elsewhere entirely.
Thanks

Found the reason. In current DryIoc version 2.9.3 adding condition to decorator makes it context dependent (which is true btw). But then context dependent service is injected as resolution call instead expression inlining. Using resolution call here messes up with resolution scopes (not yet 100% clear yet how).
So if I remove the switch to resolution call for context dependent decorators, your code works again.
Fix will be released soon. I will update my answer with the fix version.
Update with fix:
Problem is fixed in DryIoc 2.9.5

Related

What can be done about ember actions that may be fired after the user has transitioned to a new route?

I am having a problem with route-level actions that occur asynchronously occasionally not getting handled.
In my Ember app I sometimes receive the error:
Nothing handled the action 'X'. If you did handle the action, this error
can be caused by returning true from an action handler in a controller,
causing the action to bubble.
Where X is the name of some action. The problem is not that the action is bubbling or that the handler is not defined, because it works almost all the time.
The problem, rather, relates to to fact the this.send('X') is called in a promise callback, e.g., after saving a model:
model.save().then(() => {
this.send('X');
});
If the save encounters some network congestion or a delay on my server then the user might have navigated to another route by the time the promise is resolved. And that route might not have an action X defined (or worse perhaps it's the wrong action of the same name).
Is using actions here a fundamental design flaw?
If so, this would seem to severely limit the utility of actions, because they couldn't be used in any asynchronous context.
Or is there some way that transitions out of a route can delayed until any pending async stuff is resolved? (though this might create it's own undesirable symptoms)
IMHO there is not a design flaw in the case you have described. This is the nature of the promises. The same thing can happen within components and there might occur some errors related with trying to set properties on destroyed Ember components. There is a great addon I use to handle such cases: Ember Concurrency
If you take a look at this addon; you will see that there are similar cases explained, which are very similar to the one you have described. I would suggest benefiting from a popular, already heavily used library like this one instead of trying to tackle it by your own. My best regards.
For the simplicity of coding, I would suggest to move such actions to Application Controller and inject it wherever needed.
Application Controller can be injected as
import Ember from 'ember';
export default Ember.Controller.extend({
appController: Ember.inject.controller('application')
});
To use it in Template:
<button {{action 'X' target=appController}}> Login </button>
To invoke it from your code
this.get('appController').send('X');
You can also use Service to achieve this.
You can use isDestroyed guard check before calling send. But I would encourage you to use ember-concurrency addon for this use case. If you can go through How to do you check for isDestroyed? discussion forum, you will get the idea.

DryIOC and MediatR: Injection using InResolutionScopeOf for both IAsyncNotificationHandler and IAsyncRequestHandler

This question is a follow up to my previous question, DryIOC Decorator and InResolutionScopeOf
What I'm trying to do is create EF DbContext instances in the resolution scope of both IAsyncRequestHandler and IAsyncNotificationHandler, meaning the context injected in a request can't be the same as one injected in a notification (published from a request). Since the notifications are published from inside the request handlers, this nesting is creating some troubles with my desired setup.
It is worth noting that each DbContext injected in a given IAsyncRequestHandler or IAsyncNotificationHandler instance needs to be the same across their own decorators.
I've created a dotnetfiddle with my attempt at setting this up https://dotnetfiddle.net/KiFCHY. (I've ommitted decorators in this example)
It contains a RequestHandler which prints a message when it is called, and it then publishes a notification, which prints another message. However, as you can see, the notification isn't called because MediatR cannot get the IAsyncNotificationHandler instance (because it can't resolve the DbContext).
Is this setup possible?
Thanks
Found the root cause: ResolveMany<object>(serviceType) which is used in MediatR setup.
An object identifies that you need to pass run-time required serviceType. But DryIoc has an issue of using service type object instead of required type to find the matching resolution scope. And an object is definitely not assignable to IAsyncNotificationHandler<T>.
Here is the modified fiddle
Stay tuned for the fix. I will update my answer with the fix version.
Updated with fix version
The fix is released with DryIoc 2.9.2. Here is fiddle which uses it. Thanks for asking and surfacing 2 issues - real use cases matter the most.

Overriding event closure on Grails GORM domain class for unit testing

I'm working on a fresh Grails project and recently noticed the default convention in the Spring Security Core generated User class now auto-encodes the password via a beforeInsert/Update event. That's a nice, clean, DRY way of doing the encode, and also makes it impossible to forget to do so.
However, now when trying to write up some unit tests which make use of said User class, I find I either have to mock out the springSecurityService (due to the encode), or more preferably (and cleanly), I'd just override the beforeInsert/Update closure with one that does nothing. Typically in Groovy one can override a method using the ExpandoMetaClass, ala...
User.metaClass.beforeInsert = { /* do nothing */ }
...but I'm finding that the original beforeInsert continues to be called upon creating and saving a new User. This in turn causes my unit tests to blow up. It's trivial for me to just work around this and mock out the service, but the above should work. Am I missing something? Is there something different with GORM's event closures that I'm not picking up on?
In order to improve performance Grails uses reflection directly with caches method handles for invoking events and not Groovy's meta layer. The reason is that if you are saving hundreds of domain instances it can seriously hurt performance if Grails had to go through Groovy's meta layer for each event.
There are ways around this such as defining your own User class that disables the event based on a system/environment property that your test sets etc. but there is currently no way to override the methods via meta programming.
The beforeInsert closure actually is not only a method like toString() or save(), but also it is a pre-defined event supported by Gorm. Override the method will not prevent Gorm from firing the PreInsert event, which leads to the original process.
If necessary, you can replace the code in the beforeInsert with a private method and then override the private method

Google Closure Javascript testing, disable autodiscover tests

Currently i am implementing the Google closure testing possibilities.
It works as a charm.
I Define the TestCase by hand, and add the test by hand. I also create a separate runner for the tests so I can catch all the results and pass them to another function.
This function sends the results through ajax to PHP so the results can be logged in the database (also works as expected).
The problem however is that because I do this, and I load the page in the browser the tests get executed 2 times (one time because of the auto-discovery and once because i defined it in the testcase.
I would like to disable the auto-discovery, but I don't want to disable the flag in the closure library, this because when the library gets updated we need to reset the flag to false again.
So how can i disable auto-discovery without modifying the code in the closure library?
Thanks in advance!
If you look into jsusnit.js, you'll see that goog.testing.jsunit.AUTO_RUN_ONLOAD = true; is hard-coded there and you can override this variable only through closure compiler's define.
If you don't compile your test code (I don't, because of speed of iteration), the only option seems to change this to false, and redo the change on closure library updates.

Ember.js: Where is the "start" button?

I'm used to thinking about a single-page application startup happening like this: 1. Bootstrap some data into critical models, 2. Instantiate a master controller, and 3. Call it's render() method to kick things off.
How is this accomplished with Ember? Following the (meager, sigh) examples in the documentation, it seems like things sort of kick off on their own when the page loads -- templates are compiled, views render like magic when the page loads. I feel like I am missing something fundamental. It there an example online of a more complex app, say something with tabbed or dynamically loaded views?
Lightbulb, going off it is not.
I've started a blog series about getting up and running with Ember on Rails. Here's Part 1:
http://www.cerebris.com/blog/2012/01/24/beginning-ember-js-on-rails-part-1/
I hope you'll find it useful, even if you're not planning to use Ember with Rails. Most of the interesting details are client-side and thus server-independent. The posts so far cover creating an Ember.Application object, loading data dynamically through a REST interface, and then rendering an Ember view on a page in handlebars. I hope it's enough to get you started.
When you extend an ember Application object you can provide a ready function which will be called when the application starts. You have to make sure to call this._super() or else it will break your application. Check out my sample sproucore 2.0 application (ember is the new name of sproutcore 2.0).
The way that ember works is that it sets up a run loop which responds to events. Whenever an event fires, the run loop basically calls the necessary handlers and runs any bindings that need to be updated. Since everything typically happens in the run loop you often don't really write any code to update things. Instead you write bindings which are fired when needed.
Another thing I've done is use an Em.StateManager to bootstrap.
App.Loader = Em.StateManager.create({
start: Em.State.create({
enter: function(mgmt, ctx) {
// this code will execute right away, automatically
}
})
});
Since you use create instead of extend, the object will be instantiated immediately. If you define a state called start, it will be recognized as the default initial state (or you can specify another one by name). So the new StateManager object will immediately enter the initial state, and when the StateManager enters a new state, it will always look for a method of that state called enter and fire it if present.
A state manager is the natural place to initialize your app because the object provides ways for you to micromanage execution order during an async loading process without entangling yourself in too many callbacks.