How do you call a delegate exported via MEF with late binding? - dynamic

What I'm trying to do is for this to work:
GetMethod(Key key)(...some arguments...)
The "...some arguments..." varies between each call of GetMethod, including in number of parameters, so there is no specific Action<...> that I can use.
Now the GetMethod looks through the argument list to find a match within a list of Tuple and returns the second argument of the Tuple, which is the dynamic. This list was created using MEF by
<some CompositionContainer>.GetExports(new ImportDefinition(a => true, "...", ImportCardinality.ZeroOrMore, true, false))
.Select(e => (Tuple<Key, dynamic>)Tuple.Create((Key)e.Metadata["Key"], e.Value))
.ToList();
Now, it seems that the second item in the typle isn't actually an Action of the appropriate type, but rather a ExportedDelegate. Is there any way to make so that the second item is actually a correct Action, so that GetMethod(...)(...) actually does work?

Call ExportedDelegate.CreateDelegate. Pass in the type of delegate you want (ie Action). MEF uses ExportedDelegate so that you aren't restricted to using Action<> and Func<> delegates, but can use any delegate type with a matching signature.
You also probably need to specify the contract name in the constraint you pass to the ImportDefinition constructor, instead of just passing a => true.

Related

Kotlin - Dynamic Runtime Deconstructing in Kotlin

Is it be possible to create a method in Kotlin 1.5 to support dynamic object creation at runtime and support deconstruction like so:
val (A, B, C, D, E) = buildNodes("A,B,C,D,E")
The difference here is that we would need to create the methods component1() .. component5() dynamically at runtime.
https://kotlinlang.org/docs/destructuring-declarations.html
There is one problem with this. componentX() functions are used not only to get the value at runtime. They are also used to infer the type of destructured variables. You can dynamically choose in buildNodes() what will be the value of A, but you can't decide on its compile type dynamically.
So it really depends on what do you mean that these items are constructed dynamically. You can create items dynamically as long as their types are somehow predictable. For example, if your buildNodes() always returns only strings, then this is fine. In fact, you can return List<String> and it will work for at most 5 items. You can also create an interface and decide on the implementation at runtime. Or even make buildNodes() generic, so it returns different types depending on something. At the last resort, you can return Any and check the type of destructured items at the runtime.
But you can't expect that depending on the contents of the passed string, the A variable will change its compile type.

How to make Ninject choose a specific constructor without using InjectAttribute?

1) Is there a way to make Ninject select a specific constructor in code other than applying the InjectAttribute?
2) Also, how do I supply values for these arguments of the constructor?
3) Can I override these argument values on resolution or creation of the object, i.e. when I call kernel.Get<T>()?
There's the ToConstructor binding method:
Bind<IMyService>().ToConstructor(
ctorArg => new MyService(ctorArg.Inject<IFoo>()));
You can specify values on binding using 3 mechanisms:
create a binding for the dependency (Bind<IFoo>().To<Foo>())
specify a constructor argument (add a WithConstructorArgument(typeof(IFoo), new Foo()) to the end of the binding)
if i remember correctly, you can also specify it in the ToConstructor syntax like ToConstructor(ctorArg => new MyService(myFoo));
(Also see http://www.planetgeek.ch/2011/05/28/ninject-constructor-selection-preview/)
You can specify values on resolution by passing a ConstructorArgument or, preferrably, a TypeMatchingConstructorArgument (or some custom IParameter) to the resolution:
IResolutionRoot.Get<IMyService>(new TypedConstructorArgument(
typeof(IFoo),
(ctx, target) => myFooInstance));

Differences between Function that returns a string and read only string property [duplicate]

I need to expose the "is mapped?" state of an instance of a class. The outcome is determined by a basic check. It is not simply exposing the value of a field. I am unsure as to whether I should use a read-only property or a method.
Read-only property:
public bool IsMapped
{
get
{
return MappedField != null;
}
}
Method:
public bool IsMapped()
{
return MappedField != null;
}
I have read MSDN's Choosing Between Properties and Methods but I am still unsure.
The C# standard says
§ 8.7.4
A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written.
while as methods are defined as
§ 8.7.3
A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void ), and are either static or non-static.
Properties and methods are used to realize encapsulation. Properties encapsulate data, methods encapsulate logic. And this is why you should prefer a read-only property if you are exposing data. In your case there is no logic that modifies the internal state of your object. You want to provide access to a characteristic of an object.
Whether an instance of your object IsMapped or not is a characteristic of your object. It contains a check, but that's why you have properties to access it. Properties can be defined using logic, but they should not expose logic. Just like the example mentioned in the first quote: Imagine the String.Length property. Depending on the implementation, it may be that this property loops through the string and counts the characters. It also does perform an operation, but "from the outside" it just give's an statement over the internal state/characteristics of the object.
I would use the property, because there is no real "doing" (action), no side effects and it's not too complex.
I personally believe that a method should do something or perform some action. You are not performing anything inside IsMapped so it should be a property
I'd go for a property. Mostly because the first senctence on the referenced MSDN-article:
In general, methods represent actions and properties represent data.
In this case it seems pretty clear to me that it should be a property. It's a simple check, no logic, no side effects, no performance impact. It doesn't get much simpler than that check.
Edit:
Please note that if there was any of the above mentioned and you would put it into a method, that method should include a strong verb, not an auxiliary verb like is or has. A method does something. You could name it VerifyMapping or DetermineMappingExistance or something else as long as it starts with a verb.
I think this line in your link is the answer
methods represent actions and properties represent data.
There is no action here, just a piece of data. So it's a Property.
In situations/languages where you have access to both of these constructs, the general divide is as follows:
If the request is for something the object has, use a property (or a field).
If the request is for the result of something the object does, use a method.
A little more specifically, a property is to be used to access, in read and/or write fashion, a data member that is (for consuming purposes) owned by the object exposing the property. Properties are better than fields because the data doesn't have to exist in persistent form all the time (they allow you to be "lazy" about calculation or retrieval of this data value), and they're better than methods for this purpose because you can still use them in code as if they were public fields.
Properties should not, however, result in side effects (with the possible, understandable exception of setting a variable meant to persist the value being returned, avoiding expensive recalculation of a value needed many times); they should, all other things being equal, return a deterministic result (so NextRandomNumber is a bad conceptual choice for a property) and the calculation should not result in the alteration of any state data that would affect other calculations (for instance, getting PropertyA and PropertyB in that order should not return any different result than getting PropertyB and then PropertyA).
A method, OTOH, is conceptually understood as performing some operation and returning the result; in short, it does something, which may extend beyond the scope of computing a return value. Methods, therefore, are to be used when an operation that returns a value has additional side effects. The return value may still be the result of some calculation, but the method may have computed it non-deterministically (GetNextRandomNumber()), or the returned data is in the form of a unique instance of an object, and calling the method again produces a different instance even if it may have the same data (GetCurrentStatus()), or the method may alter state data such that doing exactly the same thing twice in a row produces different results (EncryptDataBlock(); many encryption ciphers work this way by design to ensure encrypting the same data twice in a row produces different ciphertexts).
If at any point you'll need to add parameters in order to get the value, then you need a method. Otherwise you need a property
IMHO , the first read-only property is correct because IsMapped as a Attribute of your object, and you're not performing an action (only an evaluation), but at the end of the day consistancy with your existing codebase probably counts for more than semantics.... unless this is a uni assignment
I'll agree with people here in saying that because it is obtaining data, and has no side-effects, it should be a property.
To expand on that, I'd also accept some side-effects with a setter (but not a getter) if the side-effects made sense to someone "looking at it from the outside".
One way to think about it is that methods are verbs, and properties are adjectives (meanwhile, the objects themselves are nouns, and static objects are abstract nouns).
The only exception to the verb/adjective guideline is that it can make sense to use a method rather than a property when obtaining (or setting) the information in question can be very expensive: Logically, such a feature should probably still be a property, but people are used to thinking of properties as low-impact performance-wise and while there's no real reason why that should always be the case, it could be useful to highlight that GetIsMapped() is relatively heavy perform-wise if it in fact was.
At the level of the running code, there's absolutely no difference between calling a property and calling an equivalent method to get or set; it's all about making life easier for the person writing code that uses it.
I would expect property as it only is returning the detail of a field. On the other hand I would expect
MappedFields[] mf;
public bool IsMapped()
{
mf.All(x => x != null);
}
you should use the property because c# has properties for this reason

Caller Contextual Binding NInject

I need to compose an instance conditionally depending on the caller.
In some cases I need a composite object instances with a "deep" type "NullService"
in other cases I instead inject a "ConcreteService"
I expect something like this:
Get<Root>.with(NullService)
or
Get<Root>.with(ConcreteService)
or better still if one could bind the construction so that it dated back to the calling context
Bind<IService>.to(ConcreteService).
Bind<IService>.to(NullService).only.whenCallerIsTypeOf(CallerWhosNeedsANullService)
is it possible?
There are two ways:
Use an own condition in case you can calculate which one should be used:
Bind<IService>.To(NullService)
.When(ctx => IsCallerWhosNeedsANullService(HttpContext.Current.Request));
Use Named bindings
Bind<Root>().ToSelf().Named("DefaultRoot");
Bind<Root>().ToSelf().Named("NullRoot");
Bind<IService>.To(ConcreteService);
Bind<IService>.To(NullService).WhenAnyAnchestorNamed("NullRoot");
Get<Root>("NullRoot");

cannot define a constructor as a bound function

class A
constructor: ->
method: ->
In the above example, method is not bound to the class and neither is constructor.
class B
constructor: ->
method: =>
In this case, method is bound to the class. It behaves as you expect a normal object method to behave and has access to all of class B's fields. But the constructor is not bound? That seems strange. So i tried the following.
class C
constructor: =>
method: =>
This doesn't compile. I would expect the syntax to be the same on all methods that are bound to a class.
I would like to regard the -> operator as a static operator and the => operator as a dynamic operator. But it doesn't seem like you can. If you could, a method with the -> operator could not be called with super. But, in actuality, you can. Why does this make sense for the syntax of an object oriented language? This seems to not agree with most object oriented languages inheritance rules.
Try looking at how the code compiles. When you use =>, the methods are bound inside the constructor. Thus, it doesn't make any sense to use => for a constructor - when would it be bound?
I'm not sure about your issue with static vs. dynamic operators, but you can definitely call methods defined with the -> operator with super. The only thing -> vs => affects is that the => ensures that this is the object in question regardless of how it is called.
Summary of comments:
Calling the difference between -> and => analogous to static vs. dynamic (or virtual) does not quite convey what those operators do. They are used to get different behavior from javascript's this variable. For example, look at the following code:
class C
constructor: ->
method1: ->
console.log this
method2: =>
console.log this
c = new C()
c.method1() //prints c
f = c.method1;f() //prints window
c.method2() //prints c
f = c.method2;f() //prints c
The difference is in the second way we call each method: if the method is not "bound" to the object, its this is set by looking at what precedes the method call (separated by a .). In the first case, this is c, but in the second f isn't being called on an object, so this is set to window. method2 doesn't have this problem because it is bound to the object.
Normally, you can think of the the constructor function automatically being bound to the object that it is constructing (thus, you can't bind it with =>). However, its worth noting that this isn't quite what's happening, because if a constructor returns an object, that will be the return value of the construction, rather than the this during the constructor.
I think you're massively confused as to the meaning of the '=>', or fat arrow.
First off though, your examples aren't actually valid coffeescript, are they? There is no -> after the class declaration. Adding one is a compiler error.
Back to the fat arrow, there's no mapping to the terms static and dynamic that I can think of, that would apply here. Instead the fat arrow is a convenient syntactic sugar for wrapping a function with a closure that contains the reference to the object you're calling the function on.
The C++ analog is to possibly to say that the fat arrow is a method for automatically creating a functor: it lets you give the function as a callback to a third party who can call it without knowing your object, but where the code invoked inside will have access to your object as the this pointer. It serves no other purpose, and has no bearing on whether a function can be overloaded, or whether it can have access to super.