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

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.

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, MediatR - DecoratorWith condition evaluated multiple times with keyed parameter

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

Glass context database null

I'm experiencing an issue with Glass Mapper in my current project that I haven't encountered before.
Directly after Sitecore has been initialized, the Database property in my GlassContext (ISitecoreContext) is null.
// After Sitecore initialization, sometimes the glass context database is not initialized yet.
if (this.glassContext == null || this.glassContext.Database == null)
{
this.glassContext = DependencyInjection.Container.Resolve<ISitecoreContext>();
// Now I have a valid this.glassContext.Database ...
}
When I ask my DI framework (Windsor, so Glass' default) for an instance, it returns me one with a valid Database property.
For the time-being I'm doing this check before retrieving any items and it only needs this check one time (after that it's good until the next initialization), but would really like to know what is causing this.
Probably interesting to know: all item requests (getting items, casting items, etc.) are done through one service which gets the ISitecoreContext initialized in its constructor.
The ItemService has lifestyle Singleton, the ISitecoreContext has lifestyle Transient
I think that your NewsService was first time injected before Sitecore has a valid context, therefor Glass also cannot be have a valid context (database). Because your ItemService has a Singleton lifetime, the constructor is only called once and also the resolving of ISitecoreContext is done once. This means, if your ItemService is resolved the first time before Sitecore has a valid context, then your glassContext will be null. After you manually set the glassContext property in the Singleton instance, the next time it won't be null (but maybe not valid because you are in another request).
I would suggest you setting both dependencies either to Transient or to PerWebRequest.
As stated in other comments, sometimes this is due to not specifying an appropriate lifestyle. Transient may give you memory leaks if you do not find an appropriate way to Release it. I personally often use the NoTrackLifestyle that ships with Glass Mapper, since it behaves more like Transient from other containers.
There are also occasions where you can attempt to resolve the service too early, this in particular can happen when running in pipeline entries etc where the context has not yet been resolved for the request. In these instances you can use either a named instance where you specify the database and / or it's name as a dependency.
Bear in mind in all cases, the sitecore context / service by default relies on the CONTEXT database, if Sitecore hasn't resolved it yet - neither will glass have.
When using it with the new Glass Delegate functionality, I have found it necessary sometimes to rely on a factory implementation that delays the getting of the service, it's not perfect, but serves it's purpose since the fluent configuration often won't have a context available at the time of instantiation. By adding a small factory, it can be delayed until the delegate code is actually called.
public interface ISitecoreServiceFactory
{
// Gets the Sitecore service from the container
ISitecoreService GetService();
}
There are also instances sometimes with this when Glass is used in the creation of SPEAK / Sheer UI dialogs.

In QtWebkit, how does a webpage's QNetworkAccessManager::createRequest() get invoked?

I'm building a Browser application using the QtWebkit and QtNetwork modules.
Let's say that it's a requirement that each webpage only be able to access resources from only a specific folder, set aside specifically for it. In this scenario, each webpage would have some kind of ID to identify it which could be used to verify that it's accessing the correct folder.
The problem is that it's not clear how exactly the createRequest() method gets invoked. If it's a signal that's emitted or something then I would be able to intercept it and add a few parameters indicating webpage ID.
As such now the only option open to me is to create a separate QNetworkAccessManager for each QWebPage and overload the createRequest() function whereas I would really like to be able to share the QNetworkAccessManager across QWebPages.
Alternate solutions would be appreciated but generally I'm also really confused about how the createRequest() method is reached.
Reference :
QNetworkAccessManager::createRequest
It's not a big deal to have a separate access manager for each web page. You don't have any measurements to show it to be a problem, so in a true Don Quixote fashion, you're fighting windmills and imaginary enemies :)
The createRequest virtual method is called by the various non-virtual request methods: get, post and put. It's a good example of the non virtual interface (NVI) pattern.

ColdSpring in Five minutes

I'm rereading ColdSpring in 5 minutes.
It says "The UserService needs the UserGateway, and the UserGateway needs the ConfigBean".
No it does not! The UserService does not need anything. It doesn't call UserGateway.
All it does is set a variable that it happens to call userGateway by coincidence, but it doesn't call the User Gateway component.
Help me understand this apparently simple scenario!
You have to remember that this starter application intentionally doesn't explain everything so as to prevent confusion. When completely configured, the sample application will initialize all three components. The UserService CFC has the responsiblity of setting and getting the User Gateway Component, the User Gateway component has the responsiblity of setting and getting the Config Bean component, and the Config Bean component is designed to set and get application settings (in this case, just datasource information).
I wouldn't fret too much over this for now if you don't understand how it all works; ColdSpring's reference guide will bring it all into focus for you.
The line "The UserService needs the UserGateway" means that one of the functions contains a variable or call that needs the UserGateway, not necessarily that the UserService has any intrinsic need for it. This is at the core of what ColdSpring does... manage dependencies. If the UserService was not configured to be injected with the UserGateway, then when a variable that "just happens" to call or need the UserGateway is created, it would not be able to find the needed UserGateway unless you manually instantiated it.
Look under "More Advanced" in the ColdSpring Quickstart Guide at "Factory Beans", for example.
The 5 minute example was just that, an example, you didn't see any calls in those functions that needed the UserGateway, but when you do have a need for it, you'll be glad it was injected for you so that you don't have to do it yourself.