Say I want to wrap a function in another function, so to add some functionality to the wrapped function. But I don't know the return type or parameters on beforehand as the methods are generated as a web service proxy.
My first train of thought was using Func<T>. But some functions might return void, in which case Action<T> would be more appropriate.
Now my question: is there a nice generic way to achieve this? Is there some pattern I need to look for?
Well, the Facade Pattern comes to mind... It's not a very automatic way of doing things, but it works. You basically just put another interface in front of the proxy and call that instead. You can then add any functionality that you desire.
Another way to approach this is with aspect oriented programming. I've used PostSharp (when it was free) to do this this in the past. You can do things like add Pre / Post processing in the function by adding an attribute to a method / property. The AOP components then use code weaving to rewrite your IL to include the code that you've referenced. Note that this can significantly slow the build process.
As you say "I don't know the return type or parameters on beforehand", I think a Dynamic Proxy is what you
need.
Unfortunately, I know about the Dynamic Proxy in Java only. But I am sure, there is something similar for C#.
Try Googling "Dynamic Proxy C#".
For example, there seems to be an implementation for C# here: http://www.castleproject.org/dynamicproxy/
So, what IS a Dynamic Proxy?
From the JavaDoc http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html#api:
A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.
Related
I am writing an AOP against an old legacy class that does not have the benefit of a built in IoC container. I am employing the power of dynamic types, using the DynamicObject derived class. When I use the
mi = obj.GetType().GetMethod(methNm, parmType);
if the parameters types (represented by parmType, above) are not exactly the types that the method was declared with, then the above GetMthod(..) will not find the method.
My question to you is:
Do you know of a way, potentially using Roslyn's semantic model, to employ the same set of rules that are used by the compiler to match the method in GetMethod(..) to the "best choice" of a method?
This logic is already implemented in Microsoft.CSharp.dll so invocations through the dynamic keyword can pick the right method too. If you can't just use that mechanism, you could look at the runtime binder code and figure out the appropriate way to incorporate it. You could call it directly (the entrypoints needed are public) without having to rebuild the code.
To lay out the problem as easily as possible, I'm trying to implement a generic pooling system that can handle an arbitrary number of concrete classes so long as they implement IBaseComponent.
So, in my class that manages the pools, I have a Dictionary of Pools:
Dictionary<Type, Pool<IBaseComponent>> pools;
As this will allow me to create as many classes that implement IBaseComponent (which is a very 'low level' interface, so to speak - so classes implementing it are not going to be compatible too terribly far) as I want, and there can be a pool for each.
Now, the issue I'm running in to is the first load of an IBaseComponent into the pool, to act as a template, so to speak.
This template object is loaded from XML, rather than code, so I do not have its actual class at compile-time, only at run time (it's defined in the XML definition and I grab the formal Type via reflection). That's all fine and dandy except, as we know, generics rely on compile-time safety.
So, using some reflection trickery I have the following:
var type = typeof(MyChildComponent);
var genericType = typeof(Pool<>);
var specificType = genericType.MakeGenericType(type);
var pool = Activator.CreateInstance(specificType );
pools.Add(T, pool as Pool<IBaseComponent>);
assuming some class:
public class MyChildComponent : IBaseComponent
The problem occurs at the last line in the first block there, when I'm adding to the pools dictionary. The cast of the instantiated pool to Pool<IBaseComponent> fails, resulting in null being inserted into the Dictionary.
My question to you fine folks is this: Is there any reasonable way around this? Any possible way, even?
If I need to load elements via some external method (XML, TXT, whatever) for at least the very first template object for a pool, for each possible concrete class that a Pool could be used for, and all I have access to is the top-level interface and formal Type of the class (both defined in the external definition file), can I do anything here?
Or is this simply not possible at all?
Are you using .Net 4+? If so, you can create an interface IPool<out T>. The out makes the generic argument covariant, which means it will accept any version of the interface with a generic argument which is T or derives from T.
For some reason co/contravariance only works with interfaces and delegates, which is why you need IPool.
Your Dictionary will become:
Dictionary<Type, IPool<IBaseComponent>>() pools;
I'm having a little trouble combining it in my head with the reflection, but I think that should work. If not, let me know and I'll spend a little more time on my test code.
One alternative option I'm toying with is modifying Pool<T> itself.
Instead of having Pool<T> store only one type of (concerete) class, I will modify it to support storing any compatible class based on an interface used for T.
So, Pool<IBaseComponent> will be responsible for storing all possible types that implement IBaseComponent.
Internally, it will store everything as an IBaseComponent, but will keep references to where each concrete type is stored (in a Dictionary of lists keyed by Type, perhaps, or even just one big linear list [although this would make resizing the "pool" for specific types a lot more complicated])
One thing I neglected to mention is that IBaseComponent exposes two points of functionality that are all I need for preparing a component for use in a "blind" fashion (ie: the factory that would be calling this pool doesn't know at compile time what types of components it's working with either, it just loads them up based on what's defined in XML, or copying from an existing object that has these components attached to it), namely: Deserialize (build component from XML/JSON/whatever) and CopyInto(IBaseComponent other) (build component by copying from another component).
So, this would still have the problem that the Pool won't be able to dynamically cast the IBaseComponent to the caller's requested Type, but that won't matter. If the caller really knows the hard compile-time type ahead of time it can do the cast. If the caller doesn't, then it wouldn't be able to do anything beyond access methods exposed by IBaseComponent anyways.
All that matters is that the IBaseComponent the Pool returns is of the correct type underneath, which this will handle.
Put simply: I'll be cutting out a bit of modern generics (interally the Pool will only work with passed-in Types, externally it will only allow T to be an interface), and replacing it will good ol' fashioned Type passing. Reflection will have to be used internally to instantiate the Pool of Types, but I figure that it's okay to expect that initializing or resizing a Pool is going to be a very costly manouever.
What is the cost of using dynamic proxies?
I do not want to clutter my project with Interface Implementations, so I am considering using Dynamic proxies created by some 3rd party library like LinFu , Castle, Unity etc. Do they generate one instance per interface or do I get one for each call.
It is a web app, so whats the performance problem in the long run.
I am also using EF 4.1 (CTP5 at the moment), so if does create proxy classes itself, which makes me wonder if I can use EF's own Dynamic Proxy creating tools.
P.S. yes my interfaces are implemented by concrete classes along with other interfaces and base classes, but sometimes I only need the interface portion of it and not the extra stuff that comes with the concrete class.
All interfaces declare just some part of an EF4.1 POCO. So just getters and setters.
The opensource Impromptu-Interface, requires c# 4.0, and creates a lightweight proxy type for each Interface and Implementation Type combo you use and keeps them cached.
So creating an interface proxy around a given implementation (an ExpandoObject counts as one type no matter how you set it up) will have a one time cost of generating the proxy type, an Activator.CreateInstance for each time you make a proxy (which isn't bad) and for each call there will be a static invocation which is what you'd have with out the proxy + a dlr dynamic invocation which is very optimized thanks to microsoft.
Looks like you need more of a stub rather than a dynamic proxy. Perhaps you might want to take a look at Moq. As far as I know it creates a different instance for every time you create a mock, don't know if internally keeps some sort of a Type cache, though. Mind you, as it's a library targeted for unit tests, so this kind of use would be probably unorthodox.
I'd like to intercept and inject custom code when calling 3rd party code in C#. I am using an external library (AutoIt) for GUI automation. The AutoIt dll is provided without source code.
All actions done with this framework are performed from a single class (AutoItClass) providing access to all the methods. I'd like to be able to inject custom code when calling methods on this class, is this possible? For example:
Log some information from within the called method.
Perform any other action from within the method (wait for X seconds).
This would be possible very simply by inheriting from this class and overriding all its methods (which is a must since this is a COM object), but this is not the preferred way. Any comments will be helpful!
I wouldn't use inheritance - you can use composition here. Create your own class which has the same methods - or in fact only the ones you're interested in - and delegate through that. That way you can be sure you won't "miss" any methods accidentally, because anything you don't implement won't be callable through the rest of your codebase... so long as you make sure the rest of your code doesn't refer to the original library class, of course.
You can investigate PostSharp, which is a commercial product that can inject IL into compiled assemblies to perform aspect oriented programming. You can define different kind of behaviour that should happen before and after a method gets executed, for example, which seems to be what you want. This way, as PostSharp handles this in a post-compilation step, you don't need to create any inherited classes from the classes that you want to intercept.
Otherwise if you want a more "pure" solution I would follow Jon's advice about creating a new class that wraps the functionality of the one that you want to intercept. (see Decorator pattern) .
Platform: C# 2.0 WinForms
I have a factory class that provides an instantiation of a particular data mapper depending on the type that I send it, the code is as such:
public static IDataMapper<T> GetMapper<T>() where T: IDto
{
Type mapperType = MapperLocator.GetMapper(typeof(T));
return (IDataMapper<T>)mapperType.Assembly.CreateInstance(mapperType.FullName);
}
I am using DynamicProxy2 to intercept method calls to my DTO objects. In my intercept method I am trying to call the above factory using the type from Invocation.TargetType. However this comes back with the exception:
The type or namespace name 'invocation' could not be found.
Obviously this is because any calls to a generic method need to know the type explicitly from what I understand at compile time. Obviously I can't do that in this case and I definitely am not going to do a switch statement across all of my DTO objects.
So, can you guys suggest a strategy or point out what I am doing wrong? I am trying to make this as generic as possible so that it could fit across all of my objects and any new ones as well as code portability to other projects.
Thanks in advance!
I'm not familiar enough with DTO to know whether or not there's enough information here for a full solution. That said, another answer is mostly correct; the C# compiler needs type information at compile time.
There is, however, a way around this: reflection. System.Reflection (particularly MethodInfo in your case I think) will allow you to write a fully generic solution.
If I've understood the question correctly, what you'd do is get the MethodInfo for that factory function, substitute in the type with MakeGenericMethod, and then Invoke that.
There is no way out of this, unfortunately; the .NET C# compiler needs to know the Type at compile time for generics; you'll have to find another method.
You could perhaps use boxing/unboxing and non-generics, but I do not know much about how you would implement this. Alternatively, you could use System.Reflection. Again, I do not know how to do this.