Difference between .Resolve and .Get in Ninject - ninject

Just wanted to get some clarrification over the difference between Kernel.Resolve and Kernel.Get in ninject.
Description for Kernel.Get states
gets an instance of the specified service by using the first binding that matches the specified constraints
Description for Kernel.Resolve states
Resolves instances for the specified request. The instances are not actually resolved until a consumer iterates over the enumeration.
In which situations might you use either of these? (Right now I'm using Get exclusively)

Kernel.Get is an extension method (or a set of extension methods to be more precise) which live in ResolutionExtensions.cs.
Kernel.Resolve is a method of IResolutionRoot.cs which is implemented by IKernel.
Only by reading the description of the methods we can recon two things:
ResolutionExtensions.Get<T>(this IResolutionRoot root) only returns the first match, which is resolved when the method is executed.
IResolutionRoot.Resolve(IRequest request) returns an IEnumerable<T>, this enumerable will resolve each match only when enumerated, and there can be more than one match.
Upon closer inspection, ResolutionExtensions.Get<T>(this IResolutionRoot root)'s implementation is:
public static T Get<T>(this IResolutionRoot root, params IParameter[] parameters)
{
return GetResolutionIterator(root, typeof(T), null, parameters, false, true).Cast<T>().Single();
}
And GetResolutionIterator's implementation is
private static IEnumerable<object> GetResolutionIterator(IResolutionRoot root, Type service, Func<IBindingMetadata, bool> constraint, IEnumerable<IParameter> parameters, bool isOptional, bool isUnique)
{
Ensure.ArgumentNotNull(root, "root");
Ensure.ArgumentNotNull(service, "service");
Ensure.ArgumentNotNull(parameters, "parameters");
IRequest request = root.CreateRequest(service, constraint, parameters, isOptional, isUnique);
return root.Resolve(request);
}
Which is essentially a wrapper method to IResolutionRoot.Resolve
So ResolutionExtensions.Get<T>(this IResolutionRoot root) is enumerating IResolutionRoot.Resolve using Enumerable.Single.
Conclusion
Kernel.Get() == Kernel.Resolve().Single()

Related

What to call an object that acts like an enter-only-once gate?

What would you call a stateful function/object x() -> bool with the following behavior: on the first call it returns TRUE, on all consecutive calls it returns FALSE. Maybe there is a pattern name already for such functionality?
The closest concept is the read-once object pattern from the Secure by Design book. Look at the paragraph below describing the object that allows to request the password only once.
A read-once object is, as the name implies, an object designed to be read once. This object
usually represents a value or concept in your domain that’s considered to be sensitive
(for example, passport numbers, credit card numbers, or passwords). The main purpose
of the read-once object is to facilitate detection of unintentional use of the data
it encapsulates.
public final class SensitiveValue {
private transient final AtomicReference<String> value;
public SensitiveValue(final String value) {
validate(value);
this.value = new AtomicReference<>(value);
}
public String value() {
return notNull(value.getAndSet(null),
"Sensitive value has already been consumed");
}
#Override
public String toString() {
return "SensitiveValue{value=*****}";
}
}
I don't know the full context of your problem but the book suggests to use the read-once object pattern in favor of security perspective. #jaco0646 also pointed out in the comments that the concept is similar to the circuit breaker pattern. Though it doesn't force for the object to always return the same value on consecutive calls. Instead, it temporary makes to obtain the stub value to give the external service some time to recover.

AOP - #Pointcut syntax: how define the method with a superclass argument/parameter

I am working with Spring Framework and AspectJ version 1.8.9
I have many Service classes, lets consider for example
CustomerServiceImpl
InvoiceServiceImpl
CarServiceImpl
The point is, each one has a saveOne method. Therefore
saveOne(Customer customer)
saveOne(Invoice invoice)
saveOne(Car car)
If I use the following:
#Pointcut(value="execution(* com.manuel.jordan.service.impl.*ServiceImpl.saveOne(Car, ..)) && args(entity) && target(object)")
public void saveOnePointcut(Car entity, Object object){}
#Before(value="ServicePointcut.saveOnePointcut(entity, object)")
public void beforeAdviceSaveOne(Car entity, Object object){
It works. Until here for a better understanding:
The first parameter represents the Entity (Car in this case) to persist
The second parameter represents the Object or target (XServiceImpl) has been 'intercepted'
Note: I need the first parameter for audit and logging purposes. Therefore it is mandatory.
To avoid do verbose and create more for each entity, I want use a 'superclass' type. I've tried with
#Pointcut(value="execution(* com.manuel.jordan.service.impl.*ServiceImpl.saveOne(Object, ..)) && args(entity) && target(object)")
public void saveOnePointcut(Object entity, Object object){}
#Before(value="ServicePointcut.saveOnePointcut(entity, object)")
public void beforeAdviceSaveOne(Object entity, Object object){
Observe the first parameter now is an Object And it does not work.
If is possible accomplish this requirement, what is the correct syntax?
I've read Clarification around Spring-AOP pointcuts and inheritance but it is about only for methods without parameter(s)
You can try to use Object+ instead of just Object. + means all classes that extend target class. So your aspect code will look like this:
#Pointcut(value="execution(* com.manuel.jordan.service.impl.*ServiceImpl.saveOne(Object+, ..)) && args(entity) && target(object)")
public void saveOnePointcut(Object entity, Object object){}
#Before(value="ServicePointcut.saveOnePointcut(entity, object)")
public void beforeAdviceSaveOne(Object entity, Object object){
I tried this with my code samples and it's work fine for all type of arguments.

WCF: Returning a derived object for a contract with base object (DataContractResolver)

I have have a WCF derived/base contract issue. I have a server interface/contract that returns a BaseThing object:
[OperationContract]
BaseThing Get_base_thing();
The server that implements this has a DerivedThing (derived from BaseThing) and wants to return this as a BaseThing. How to tell WCF that I only want to transport the BaseThing part of DerivedThing?
If in Get_base_thing I just return a reference to a DerivedThing then I get a SerializationException server side.
I think I need to define a DataContractResolver and I looked at the MSDN article Using a Data Contract Resolver but this is not 100% clear (to me a least).
How should my DataContractResolver look to tell WCF to only transport the base part of the derived object I pass it?
Is there some way to do this more simply just with KnownType attribue?
KnownType will not resolve this issue.
It sounds as if you have a serious divergence between the object model you're using at the server and the service contracts you're using. There seems to be 3 possible solutions:
1) Data Contract Resolver as you've identified to make it automatic across all your operations. There are a number of examples out there including this one: http://blogs.msdn.com/b/youssefm/archive/2009/06/05/introducing-a-new-datacontractserializer-feature-the-datacontractresolver.aspx.
2) Align your object model to better match your service contracts. That is, use containment rather than inheritance to manage the BaseThing-DerivedThing relationship. That way you work with DerivedThing at the server and simply return DerivedThing.BaseThing over the wire. If BaseThing needs to get transmitted from client to server, this will also work better.
3) Use explicit conversion using something like AutoMapper so it is obvious in your operations that there is a divergence between the objects being used at the server and those exposed to the outside world.
After posting I also found this SO identical question How to serialize a derived type as base. The unaccepted second answer by marc for me is the easiest way to resolve this issue. That is:
Decorate the derived class with [DataContract(Name="BaseClass")]
Note that this solution means that derived will transport as base for all every case of transport of this object. For me that was not an issue if it is then you need to go the DataContractResolver route.
Some notes on the DataContractResolver route:
1. This enables you to pass the derived as derived on some calls but as base on other - if you need to do that - if not use about Name= approach.
2. I get an exception using the DeserializeAsBaseResolver from the datacontractrsolver article as it stands because the knownTypeResolver returns false. To fix that I ignor the return value of that call and always return true from TryResolveType. That seems to work.
3. I initially thought that because we were serializing as base that I didnt need [DataContract] on the derived class. That was wrong. The object is serialized as the derived object and derserialized as a base object - so you must decorate the derived with [DataContract] but don't mark any fields as [DataMembers] to avoid them being unnecessarily serialize.
4. If you have a command line host and a service host then you need the code to insert the contract resolver in both. I found it useful to put this as a static in my resolver.
5. Note that that the "Get_gateway_data" string in the call to cd.Operations.Find("Get_gateway_data") is the name of the contract method that returns the object concerned. You will need to do this for each call that you want this behaviour.
Final code for this approach:
public class DeserializeAsBaseResolver : DataContractResolver {
public static void Install(ServiceHost service_host) {
// Setup DataContractResolver for GatewayProcessing to GatewayData resolution:
ContractDescription cd = service_host.Description.Endpoints[0].Contract;
OperationDescription myOperationDescription = cd.Operations.Find("Get_gateway_data");
DataContractSerializerOperationBehavior serializerBehavior = myOperationDescription.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (serializerBehavior == null) {
serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
myOperationDescription.Behaviors.Add(serializerBehavior);
}
serializerBehavior.DataContractResolver = new DeserializeAsBaseResolver();
}
public override bool TryResolveType(Type type, Type declaredType,
DataContractResolver knownTypeResolver,
out XmlDictionaryString typeName,
out XmlDictionaryString typeNamespace) {
bool ret = knownTypeResolver.TryResolveType(type, declaredType, null, out typeName, out typeNamespace);
//return ret; // ret = false which causes an exception.
return true;
}
public override Type ResolveName(string typeName, string typeNamespace,
Type declaredType, DataContractResolver knownTypeResolver) {
return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? declaredType;
}
Host code (service or command line):
using (ServiceHost service_host = new ServiceHost(typeof(GatewayServer))) {
// Setup DataContractResolver for GatewayProcessing to GatewayData resolution:
DeserializeAsBaseResolver.Install(service_host);
// Open the host and start listening for incoming messages.
try { service_host.Open(); }

Velocity Eventhandler

in velocity, when you do $object.variable if it not be able to find the getter function to
access it or the getter returns a null. it will just show $object.variable explicitly on the page
I know there is a quiet reference, but I don't want to add ! sign to thousands of variables.
I have tried InvalidReferenceEventHandler, NullValueHandler they all didn't get called.
I wander is there a specific type of Eventhandler for this.
Many thanks
The above seems to be a valid choice as well. However here is another option:
public class AppSpecificInvalidReferenceEventHandler implements
InvalidReferenceEventHandler
{
private static final Logger LOGGER =
Logger.getLogger(AppSpecificInvalidReferenceEventHandler.class);
#Override
public Object invalidGetMethod(Context context, String reference,
Object object, String property, Info info)
{
reportInvalidReference(reference, info);
return "";
}
#Override
public boolean invalidSetMethod(Context context, String leftreference,
String rightreference, Info info)
{
reportInvalidReference(leftreference, info);
return false;
}
#Override
public Object invalidMethod(Context context, String reference, Object object,
String method, Info info)
{
if (reference == null) {
reportInvalidReference(object.getClass().getName() + "." + method, info);
} else {
reportInvalidReference(reference, info);
}
return "";
}
private void reportInvalidReference(String reference, Info info)
{
LOGGER.info("REFRERENCE: " + reference + " Info <" + info + ">");
}
}
You'll also need to add the following to your velocity.properties file:
eventhandler.invalidreferences.class=path.to.package.AppSpecificInvalidReferenceEventHandler,org.apache.velocity.app.event.implement.ReportInvalidReferences
You might be surprised at the results though, so it will likely need fine-tuning dependent upon your needs.
I'm basing this off of Engine-1.7 code.
It seems that when an invalid method is called that the utility method EventHandlerUtil.invalidGetMethod is called. This method creates a new InvalidGetMethodExecutor (this is an inner class on InvalidReferenceEventHandler). Eventually this chains down into a call to invalidReferenceHandlerCall which eventually iterates over any handlerIterators which have been defined. Unfortunately I don't know enough about the internals of Velocity to tell you how to inject these values though. My guess is that the user list will suggest a way to override this behavior or a suggestion will be to use / implement a custom tool.
Edit:
According to the Developer Guide you can do the following. You'll need to write some code to deal with it, but it shouldn't be too difficult:
Pluggable Introspection
runtime.introspector.uberspect = org.apache.velocity.util.introspection.UberspectImpl
This property sets the 'Uberspector', the introspection package that handles all introspection strategies for Velocity. You can specify a comma-separated list of Uberspector classes, in which case all Uberspectors are chained. The default chaining behaviour is to return the first non-null value for each introspection call among all provided uberspectors. You can modify this behaviour (for instance to restrict access to some methods) by subclassing org.apache.velocity.util.introspection.AbstractChainableUberspector (or implementing directly org.apache.velocity.util.introspection.ChainableUberspector). This allows you to create more interesting rules or patterns for Uberspection, rather than just returning the first non-null value.

Will WCF use the same ParameterInspector instance to handle BeforeCall and AfterCall?

If I create a class that implements IParameterInspector, and insert it into the WCF pipline using a custom ServiceBehavior, will the same instance of the class be used when invoking BeforeCall and AfterCall? In other words, can I establish state about the current invocation during BeforeCall that I can access in AfterCall, and be sure that the response will come to the same instance?
Note _stateValue in the sample code below? Can I depend on a mechanism like this?
class OperationParameterInspector : IParameterInspector
{
public int _stateValue;
public object BeforeCall(string operationName, object[] inputs)
{
_stateValue = (int) inputs[0];
return null;
}
public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
int originalInput = _stateValue;
return;
}
}
Passing state related to a particular call is the purpose of the return value from BeforeCall and the correlationState argument of AfterCall. The WCF infrastructure ensures that whatever object you return from BeforeCall is then passed into AfterCall via the correlationState, after the operation has completed.
As your subsequent comment suggests, the problem with using instance state in the inspector object is that instances may be shared between concurrent requests in some scenarios. However, I don't think there are any scenarios where a single operation request would be served by different parameter inspector objects in BeforeCall and AfterCall.