Set a StructureMap Nested Container to resolve unique object instances by default - asp.net

According to StructureMap's documentation the default behavior of containers is that a Parent Container resolves a new object instance each time one is requested and Nested Containers resolve the same object instance.
In 99% of cases this is fine - however I'm keen to know if there's a way I can set a nested container to behave similarly to the Parent Container and resolve new object instances by default - without the need to rely on the .AlwaysUnique() method.
Is this possible or is .AlwaysUnique the only way to do it on an object by object basis?

I think that beside explicit specification of nested container configuration there is no support for that as it was designed around creating temporary context for objects resolution. IIRC in SM 3.0 HttpContextScoped lifecycle was implemented with usage of nested container.
If you want to have the flexibility of resolving existing object from the container or creating a new one you can implement factory that would handle it for you through injected context into the factory or based on explicit method call (factory.Create() or factory.ReuseIfExistsOrCreate()).
Hope this helps!

Related

QML: Is there any reason to set a context property instead of setting a property on the root object, when the latter way has advantages?

Consider this setting of a context property:
engine.rootContext()->setContextProperty("text", "hey");
And this qml code:
Text {
text: text
}
This doesn't work as expected, because of the name shadowing.
One fix is to name the context property _text - then there's no problem. But I don't want to have to remember this naming convention (both to remember to use it, and to remember what it means when I read it).
Another fix is to change the context property into a property on the root object:
engine.rootObjects()[0]->setProperty("text", "hey"); // [1]
and in the QML:
text: window.text
Is there any reason to avoid the latter way when it seems so good?
Setting a context property has one disadvantage - it requires recompilation of the C++ code. Naturally, that's a non-issue if you are exposing a C++ object, which is the typical and only logical use case.
It may be seen as an advantage that the context property can be available before the root object is created, but in most cases it will work equally well if it is just a property of the root object. And I clarify that "most cases" here means that object properties are typically not being set from C++ and not being used in initial bindings, since obviously, if you do that, the initial binding will fail to resolve the property when the object is created, before the property is being set. Also note that when creating QML object form C++, you can use the two step process - prepare the object, then set any properties and so on, and only then complete the object creation, which will delay binding evaluations, so you won't have that problem.
Another possible advantage is that you can have more than one root object, thus if the property is in the root context, then all root objects and their subsequent children will be able to resolve it.
Another possible advantage - when you set a context property, you typically get assistance from the IDE, as that object is now known to be out there, so you will have auto-complete for that property name. It sometimes works for parent object properties as well, but it is a hit-or-miss.
As for the speed of access, I am not so sure that a context property would be faster than root object property. I haven't tested it, but it is just logical. Any object property is a de-facto context property, as each object has its own context. Considering that, as you recently discovered, context properties can be shadowed by object properties, it is thus logical to conclude that a context property lookup simply goes down the object contexts until it finds that property rather than going straight to it, so if anything, resolving context properties should be a tad slower than resolving root object properties, because they go one step deeper.
Until line [1] has been executed, window.text is undefined, so at first, you get an error message on the console (though once it gets to executing line [1], the text is displayed). But if you use a context property, you're free to create it before loading the QML file, which removes the problem.

How can I register a specific singleton instance with Caliburn Micro's Simple Container?

I've registered a type in Caliburn Micro using it's Simple Container as a singleton.
_container.Singleton<MyType>("MyType");
Now I've realized I need to pass in some specific constructor parameters, so I created an instance of the registered class, configured it, then tried to use RegisterSingleton. And realized it doesn't seem to let me pass a specific instance. I've looked at the docs and don't quite understand how this was supposed to work.
How can I get it to use this specific instance for the singleton?
Call SimpleContainer.RegisterInstance with the service type, key and implementation.
For example:
_container.RegisterInstance(typeof(MyType), "MyType", new MyType());
The simple container is documented here.

Thread safety and MEF catalog

I'm using MEF (the one in .Net Framework, not System.Composition Nuget) to do DI in asp.net. I'm encountering memory leaks like many have previously due to MEF rooting NonShared IDisposable (e.g. link)
I'm looking at using child containers to rectify this by having
Child containers create (NonShared) parts specific to a single request
Parent container (referenced as an export provider) containing the shared parts
So something like:
CompositionContainer GetRequestContainer(CompositionContainer parent, ComposablePartCatalog catalog)
{
return new CompositionContainer(catalog, parent);
}
Originally, I built a single catalog with Shared and Non-Shared parts: To create a child container with only NonShared parts I used FilteredCatalogs built off the parent CompositionContainer's catalog so that the filtered catalog contains only the NonShared parts.
This resolved the memory leak since I could Dispose() the child container at the end of a request whcih would then free up all my NonShared IDisposable objects. Great.
However, calling childContainer.GetExportValues returns duplicates because there are parts from the parent containers catalog as well as the child container's catalog.
Now I want to create 2 catalogs explicitly:
Global catalog for all shared parts
Local catalog for all NonShared parts
I suspect the IDisposable tracking is at the container level so I should be safe passing around single instance of each catalog, but that is what I wanted to ask here and confirm:
Is it threadsafe to have a single instance of a catalog backing all instances of containers?
So N concurrent WebRequest instances are serviced by N + 1 CompositionContainer instances (child+parent), all backed by 2 global catalog instances.
CompositionContainer parent = new CompositionContainer(Static.Global, CompositionOptions.IsThreadSafe);
CompositionContainer GetRequestContainer(CompositionContainer parent)
{
return new CompositionContainer(Static.Local, parent);
}
It is perfectly safe to use the same catalog instance with several CompositionContainer instances (by the way, this is true regardless of whether you use the CompositionOptions.IsThreadSafe option when creating your container).
The reason it's safe to do so is because the catalog merely defines the "potential" of parts that can be created by the container, and doesn't hold any data regarding whether they have been instantiated or not. It's the container's responsibility to track such things.

OpenStack - Check for Availability of Container C# .NET

I have integrated openstack to my .net solution. I am using CloudFilesProvider to create and delete a container. Is there any provision to check for the existence of a container using C#.
I know it is possible to check by getting ObjectStore and find ContainerExists property. But i am not sure how to get this property filled.
Any help will be greatly appreciated.
ObjectStore is an enumeration that defines the possible values returned by calls like IObjectStorageProvider.CreateContainer. For example, you could get an ObjectStore by attempting to create the container you're checking, and the return value would be ContainerExists if the container already exists. Unfortunately you could always end up with ContainerCreated returned by that call, i.e. if you use CreateContainer to check for a container's existence, then even if the container didn't exist before "checking", it would afterwards.
While it's definitely not clean, one option is calling GetContainerMetadata. The call will throw an ItemNotFoundException if the container doesn't exist.
Are you, by chance, using this Container as a CDN?
When deleting a CDN, you must also call the method "DisableCDNOnContainer" against the Container. Also, if you call the method "ListCDNContainers", you must filter out deleted CDN Containers by checking the property "CDNEnabled".
This is because deleted Containers "hang around" until their ttl expires.

React to change on a static property

I'm re-writing an MXML item renderer in pure AS. A problem I can't seem to get past is how to have each item renderer react to a change on a static property on the item renderer class. In the MXML version, I have the following binding set up on the item renderer:
instanceProperty={callInstanceFunction(ItemRenderer.staticProperty)}
What would be the equivalent way of setting this up in AS (using BindingUtils, I assume)?
UPDATE:
So I thought the following wasn't working, but it appears as if Flex is suppressing errors thrown in the instanceFunction, making it appear as if the binding itself is bad.
BindingUtils.bindSetter(instanceFunction, ItemRenderer, "staticProperty");
However, when instanceFunction is called, already initialized variables on the given instance are all null, which was the cause of the errors referenced above. Any ideas why this is?
You have 2 options that I am aware of:
Option 1
You can dig into the code that the flex compiler builds based on your MXML to see how it handles binding to static properties. There is a compiler directive called -keep-generated-actionscript that will cause generated files to stick around. Sleuthing through these can give you an idea what happens. This option will involve instantiating Binding objects and StaticPropertyWatcher objects.
Option 2
There is staticEventDispatcher object that gets added at build time to classes containing static variables see this post http://thecomcor.blogspot.com/2008/07/adobe-flex-undocumented-buildin.html. According to the post, this object only gets added based on the presence of static variables and not getter functions.
Example of Option 2
Say we have a class named MyClassContainingStaticVariable with a static variable named MyStaticVariable and another variable someobject.somearrayproperty that we want to get updated whenever MyStaticVariable changes.
Class(MyClassContainingStaticVariable).staticEventDispatcher.addEventListener(
PropertyChangeEvent.PROPERTY_CHANGE,
function(event:PropertyChangeEvent):void
{
if(event.property == "MyStaticVariable")
{
someobject.somearrayproperty = event.newValue as Array;
}
});
I think you need to respond to the "PropertyChanged" event.
If you're going to do that, use a singleton instead of static. I don't think it will work on a static. (If you have to do it that way at all, there are probably a couple ways you could reapproach this that would be better).
var instance:ItemRenderer = ItemRenderer.getInstance();
BindingUtils.bindProperty(this, "myProperty", instance, "theirProperty");
After fiddling with this for a while, I have concluded that this currently isn't possible in ActionScript, not even with bindSetter. It seems there are some MXML-only features of data bindings judging by the following excerpt from the Adobe docs (though isn't it all compiled to AS code anyways)?
You cannot include functions or array
elements in property chains in a data
binding expression defined by the
bindProperty() or bindSetter() method.
For more information on property
chains, see Working with bindable
property chains.
Source: http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_7.html
You can create a HostProxy class to stand in for the funciton call. Sort of like a HostFunctionProxy class which extends from proxy, and has a getProperty("functionInvokeStringWithParameters") which will invoke the function remotely from the host, and dispatch a "change" event to trigger the binding in typical [Bindable("change")] Proxy class.
You than let the HostProxy class act as the host, and use the property to remotely trigger the function call. Of course, it'd be cooler to have some TypeHelperUtil to allow converting raw string values to serialized type values at runtime for method parameters (splitted by commas usually).
Example:
eg.
var standInHost:Object = new HostFunctionProxy(someModelClassWithMethod, "theMethodToCall(20,11)");
// With BindingUtils.....
// bind host: standInHost
// bind property: "theMethodToCall(20,11)"
Of course, you nee to create such a utlity to help support such functionality beyond the basic Flex prescription. It seems many of such (more advanced) Flex bindings are usually done at compile time, but now you have to create code to do this at runtime in a completely cross-platform Actionscript manner without relying on the Flex framework.

Resources