What's the best way to implement a dynamic proxy in C#? - c#

I've got a need to create a dynamic proxy in C#. I want this class to wrap another class, and take on it's public interface, forwarding calls for those functions:
class MyRootClass
{
public virtual void Foo()
{
Console.Out.WriteLine("Foo!");
}
}
interface ISecondaryInterface
{
void Bar();
}
class Wrapper<T> : ISecondaryInterface where T: MyRootClass
{
public Wrapper(T otherObj)
{
}
public void Bar()
{
Console.Out.WriteLine("Bar!");
}
}
Here's how I want to use it:
Wrapper<MyRootClass> wrappedObj = new Wrapper<MyRootClass>(new MyRootClass());
wrappedObj.Bar();
wrappedObj.Foo();
to produce:
Bar!
Foo!
Any ideas?
What's the easiest way to do this?
What's the best way to do this?
Thanks so much.
UPDATE
I tried following Wernight's recommendation and implement this using C# 4.0 dynamic proxies. Unfortunately, I'm still stuck. The point of the proxy is to mimick the other interface which is (normally, usually) expected. Using DynamicObject requires me to change all the clients of this to use 'dynamic' instead of 'ISecondaryInterface'.
Is there a way to get a proxy object, such that when it wraps an A, it advertises (statically?) that it supports A's interface; and when it wraps a B, it advertises that is supports B's interface?
UPDATE 2
For example:
class MySecretProxy : DynamicObject, ISecondaryInterface
{
public override void TryInvokeMember(...) { .. }
// no declaration of Bar -- let it be handled by TryInvokeMember
}

.NET 4 DynamicObject can help you achieving that.
Earlier .NET framework can use:
Aspect#
Encase AOP
Spring.NET
Aspect.NET
AspectDNG
Dynamic Proxy
Compose*
Loom.NET
PostSharp
Each of these frameworks make use of a number
techniques to the injection of code
both before and after execution of a
method. These generally fall into 4
categories.
MSIL injection – Here we inject MSIL code into the body of the
method being executed. (Post sharp)
Runtime dynamic injection – Using techniques such as reflection we
invoke methods dynamically.
Type builder injection – Related to runtime injection, we create a type based on
the type we wish to proxy and then marshal requests through this type. (Dynamic Proxy)
Container injection – Requests pass through a container
which invokes code before and after our method being executed.
See the full article.
I know that Castle Project's Dynamic Proxy is often used (like in Moq just to name one large project).
REPLY TO UPDATED TOPIC
What you wrote will not compile. Dynamic proxies are runtime generated code, so you'll have to create a concrete instance of the class you're proxying some way or another. May be you're looking to do AOP (aspect-oriented programming).
class MySecretProxy<T> : DynamicObject, T where T : new()
{
private T _instance = new T();
public override void TryInvokeMember(...) { ... }
}
MySecretProxy<Bar> bar;

Have you looked at the Castle project's DynamicProxy? It may provide what you're ultimately trying to achieve. See http://www.castleproject.org/dynamicproxy/index.html
It's also open source so you could even fork it if required.

You can do this with RealProxy if the target Type is an interface or derives from MarshalByRefObject.

You may want to look at linfu which contains a dynamic proxy mechanism.

I know the proxies that used by nhibernate for lazy loading
Castle
Linfu
Spring ByteCode

Related

Intercept Method Invocation or Property Change with Reflection

I'm trying to create a generic class that will fire an event whenever a method is called or a property is accessed or changed. It may also fire events in response to other changes or actions being taken, but for now, that'll be it.
In order to do so, I'd like to intercept every method call and every property access/change, but I have no way of knowing exactly which methods I'm handling. There's no given interface that defines every generic type T I'll be working with, so I have to use reflection. Here's how I envision it (Trigger<T> is the class, and generic would be of type T):
public Trigger()
{
this.generic = default(T);
foreach (MethodInfo m in generic.GetType().GetMethods())
{
// This is pseudocode, since I can't just set MethodInfo to a new method
m = delegate()
{
m.Invoke(this.generic, null);
if (MethodCalled != null)
MethodCalled(this, eventArgs /*imagine these are valid EventArgs*/);
};
}
}
I realize that I've grossly oversimplified the problem. First off, I'd have to deal with parameters. Second, you can't just override a method programmatically like that. And third, I haven't even started on properties yet. Plus, I'd have to be changing these things for only the object, not the entire type, so I'm not sure how that works either.
I've done my research, and all I find is confusing content. I realize that I'm somehow supposed to be using AOP, but I've never done anything other than OOP and procedural programming, so I'm rather lost in this dense jungle of knowledge. It sounds like I'll need to use PostSharp or Unity, but I still have no clue how after looking at all this, and this, and these two, and also this (all separate links, per word).
Is there any simpler way to do this? And can I even do it without using interfaces or predefined classes?
It's generics that make my problem particularly complicated. If I could just have a class inherit from T, and then use a proxy to capture its method calls and property accesses/changes, then things would maybe be a tad simpler, though I still lack the fundamental understanding of AOP to do that. Any help you can provide would be much appreciated. If possible, please write your answer at a beginner level (though I know my OOP fairly strongly, like I said, I don't know the first thing about AOP).
Without resorting to a full-on AOP framework that uses post-bulid IL weaving, you can use Castle's DynamicProxy and create an interceptor. You can find plenty of tutorials online:
Simple AOP
Short tutorial on CodeProject
This extensive one.
For your interceptor to work, you will need to make sure your generic class's methods and properties are virtual. This allows the DynamicProxy's runtime weaving code to generate a proxy that wraps your class.
You can do it like that using NConcern, a new open source AOP Framework on which I actively work.
public class Trigger<T> : Aspect
{
static public event EventArgs MethodCalled;
static private Trigger<T> m_Singleton = new Trigger<T>();
//Auto weaving aspect
static Trigger()
{
Aspect.Weave<Trigger<T>>(method => method.ReflectedType == typeof(T));
}
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//define an advice to trigger only when method execution not failed
yield return Advice.Basic.After.Returning(() =>
{
if (MethodCalled != null)
{
MethodCalled(this, null);
}
});
}
}
public class A
{
public void Test()
{
}
}
int main(string[] args)
{
Trigger<A>.MethodCalled += ...
new A().Test();
}
You can find a similar Example code source here : Example of observation pattern implemented with NConcern
NConcern AOP Framework is a light framework working at runtime. It work with code injection avoiding factory/proxy by inheritance. It allow you to add aspect to a class by injecting code you can create using simple delegate, ILGenerator or expression tree (linq) before/after or around a method. It can handle sealed class, sealed method, virtual method or explicit/implicit interface implementation.
Into my example, I create a class derived from Aspect (abstract class).
When a class derived from Aspect, it have to implement Advise method by returning an instance of Advice (Before/After/After.Returning/After.Throwing or Around). Each can be created with Delegate or Expression to define what you need to do on method interception.
public class MyAspect : IAspect
{
//this method is called initially (not on interception) to rewrite method body.
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//this block of code means that method will be rewrite to execute a write method name to console before original code only for public methods
if (method.IsPublic)
{
yield return Advice.Basic.Before(() => Console.WriteLine(method.Name));
}
}
}
Usage
//attach myaspect to A class. All methods of A will be passed to Advise method to process methods rewriting.
Aspect.Weave<MyAspect>(method => method.ReflectedType == typeof(A));
//detach myaspect from A class. All methods will be rewrite to give back original code.
Aspect.Release<MyAspect>(method => method.ReflectedType == typeof(A));

Do DynamicProxy classes work well with intellisense/type safety?

I was looking at using DynamicProxy classes, and I'm fairly new to this concept. Before I got too far down this road, I was wondering how well these classes work with IntelliSense and type safety?
I'm just afraid of using something like Castle DynamicProxy (or some other ones), and after setting everything up finding out that using my objects provides no IntelliSense or type safety. Can anyone shed any light on this?
I'm looking for a straight answer on how DynamicProxy classes are
used, and whether or not they support intellisense, and if so... how?
Well, in explaining how DynamicProxy classes work, you'll have a clear understanding to why they are type safe, and how they are able to work with intellisense so nicely.
Firstly, let's understand what a DynamicProxy actually is. A proxy class is a class that handles member calls on behalf of another class. This is either done through inheritance (most common) or through composition. So, if you were to hand-write a proxy class, here is what it could look like:
public class Customer
{
public virtual string Name { get; set; }
// etc...
}
public class CustomerProxy : Customer
{
public override string Name
{
get
{
// Do additional functionality...
return base.Name;
}
set
{
// Do additional functionality...
base.Name = value;
}
}
}
Two (2) key features play a crucial role in this working appropriately, inheritance and polymorphism. So, to use the Customer class seamlessly, a ProxyGenerator simply would create an instance of the CustomerProxy class, but return it as a type of Customer. It would basically be the same thing as doing Customer customer = new CustomerProxy();. The "dynamic" portion doesn't really have anything to do with the .NET dynamic keyword, but instead should read "Runtime", because it simply means that the proxy class is generated at runtime (while the application is running), instead of at compile-time. Oh, and in case you are wondering how it does this, it uses System.Reflection.Emit
That's the simple version of what a DynamicProxy is. Different frameworks offer different features when it comes to creating these proxy classes. For example, in Castle Windsor's DynamicProxy one could create Mixins and apply additional interfaces to these proxy classes -- that is, your generated proxy class could potentially look something like this: public class CustomerProxy : Customer, ISomeInterface { ... }, even though the Customer class itself did not implement the ISomeInterface. Here is a really good resource for Castle's DynamicProxy (http://kozmic.net/dynamic-proxy-tutorial/). It goes through the various features and use cases for those features.
It is and type safe so intellisense should work just fine with it.
see this example: DynamicProxy tutorial
you can see that they use generics for instanciating the proxy classes. It means that its fully typed so you've got nothing to worry about.
Proxies can be seen as call interceptors (depending of the kind of proxy implementation), so when you are writing your code is like you were working with a defined interface or class so you will get intelliSense.
Then, depending of the kind of proxy you implement "some" calls to the class/interface members will be intercepted.
[Edit]
If you use the dynamic keyword, for example when implementing a dynamic proxy using a DynamicObject obviously you will not have intelliSense, but this caused by the nature of the dynamic keyword and not by the proxy itself. You can take a look at this link to see how to implement a Proxy using a DynamicObject

Access interface methods without referring the class

Say I have an Interface like this in a project called "Interface":
public interface TestInterface
{
string Operation();
}
and class which implements it. This class is located in another project "Class":
public class TestClass : TestInterface
{
public TestClass() { }
public string Operation()
{
return "This is an Operation";
}
}
My client does something like this (which is again in a different project "Client"):
class Program
{
static void Main(string[] args)
{
TestInterface i = new TestClass();
i.Operation();
}
}
My question is related to this line:
TestInterface i = new TestClass();
By adding this line, I'm actually forced to add a references to both "Interface" as well as "Class" projects from my "Client" project. So why all this fuss? Can't I directly refer to the "Class" without keeping the "Interface" in between? Is there any way to access the methods via Interface only (without making a reference to the implementation Class)? Am I missing something here?
Is there any way to access the methods via Interface only
Yes, there is. You can dynamically load an assembly with TestClass without referencing it, create its instance via Activator.CreateInstance and cast it to interface type:
var assembly = Assembly.Load(...);
var typeFromAssembly = assembly.GetTypes()...;
var myInterfaceVar = (TestInterface)Activator.CreateInstance(typeFromAssembly);
...or... you may use one of existing DI-frameworks (e.g. MEF) and do the same thing more right way:
[Import]
private TestInterface myInterfaceField;
or:
var myInterfaceVar = compositionContainer.GetExportedValue<TestInterface>();
Depending of the way you prefer, you may ask more concrete question.
In that particular sample, there is no advantage.
But imagine a method:
public void Foo(ITestInterface handler)
{
handler.Operation();
}
Now, Foo operates only on the interface and it doesn't care what concrete class implements this interface. You could now call Foo with an instance of TestClass or with TestClass2, which could be defined in a different assembly.
you can achieve the behavior you have described via using IOC.
Unity is a dependency injection container which allows to create instances without manually creating instances.
For instance, if you were to register your class and interface to unity, you would directly use the interface;
TestInterface i = Container.Resolve<TestInterface>();
To make your code completely independent from implementation of TestInterface use Dependency Inversion. This could be achieved by some Dependency Injection framework.
E.g. with Unity you can configure implementation via xml
<register type="TestInterface"
mapTo="Foo.Bar.TestClass, Foo.Bar" />
And your code will depend only on Unity (no references to implementation):
TestInterface i = Container.Resolve<TestInterface>();
You have interface so that your app can have plug in's..
So basically you share your Interface dll to anyone who wants to make a plugin app for your app and then you can cast that new plugin class to the interface and invoke methods on it..
If you dont cast the class to the interface,how on earth are you going to make the plugin class work for your app..

How to implement saving/loading interface with parameterized constructor?

I know interfaces cannot define constructors. Here's what I wish I could do:
public interface SavableObject {
void Save(ObjectSaver saver);
SavableObject(ObjectLoader loader); //This, obviously, doesn't work
}
//Loading an object inside ObjectLoader:
T LoadObject<T>() where T : SavableObject {
return (T)Activator.CreateInstance(typeof(T), this);
}
And I could do this if I took out the line that didn't work, and there would just be a runtime error when trying to load (or possibly save, if I put an assert in there) the object if it didn't have the constructor. I'm just wondering if there's any way to require a class to have a particular constructor that can be used with the Activator. Can I use a custom attribute somehow, and require that attribute to be on the class? Or must I rely on runtime checks to load and save data?
I know I could have a parameterless constructor and a Load(ObjectLoader) method but I don't necessarily want to have a parameterless constructor available to abuse for other purposes.
what about ISerializable?
In brief I suggest you use generics as most factories do.
public interface SavableObject<T> : where T : new
{
void Save(IObjectSaver<T> saver);
SavableObject<T> Load(ObjectLoader loader); //This, obviously, doesn't work
}
However, you seem to have turned it on it head. The class is doing what factory must do. So I do not think it is such a good idea to pass the factory to the entity itself and that is part of the problem you are experiencing in the design.
If you are not afraid of using Reflection, like Activator that you have shown, you can do little trick I tend to use:
Make parameterless constructor that is protected
Make Load method, that is also protected (or private, I tend to use virtual protected so I support inheritance)
Create new object using this non-public constructor (through reflection - you can't create instance of your class "just like that" using new operator)
Invoke load method (also using reflection - no one will call it later).
I don't know if this will work for you, but I used that method when I needed to deserialize pretty big game state and it was pretty fast, eventhough all this reflection (for many reasons I did not wanted to use built-in serialization methods and Factory Pattern wouldn't do, so I tend to treat this method as something that may be useful if other methods fail, on the other hand, if I could - I would probably use built-in serialization for simplicity).
How about adding a property on your interface:
public interface SavableObject
{
void Save(ObjectSaver saver);
ObjectLoader ObjectLoader {get; set;}
}
Then in your factory:
T LoadObject<T>() where T : SavableObject
{
var result = (T)Activator.CreateInstance(typeof(T));
result.ObjectLoader = this;
return result;
}
Based on your question and comments.
I think you should do it at runtime using reflection.
Combining constructors and interfaces is ilogical from its core. Interface is about what concrete instance can do, not how to initialize it. This can only be achived using abstract class.
Maybe using factory to create instance of the class?
Also I don't think you can get better speed than default ISerializable implementation. Unless you are .NET GURU and have years of time for it.
Short answer: It's not possible, I guess. There are no attributes or generalizations I can use to require a specific kind of constructor on a class.

C#/.Net enforcing (or just 'hint to fellow developers') that a class method is only supposed to be called from another specific class?

I'm doing some internal domain-specific library development at the moment, and incidentally the stuff i'm trying to model mimicks "class" and "object" relations fairly well. So objects of my C# class MyClass should sort of act like a domain specific class for objects of my C# class MyObject who play the part of object or instance. Now I would like the code in MyObject to access methods of MyClass, which should not be accessible to other classes/code in the project. Any ideas how to enforce this, asside from documenting it at hoping my fellow developers will respect this.
I hope I made my question clear enough, otherwise let me know.
Best regards!
You could always split MyClass and MyObject up into another project, and define MyClass and/or MyObject as an internal class. That way it can only be accessed by other objects in that assembly.
See: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
The standard approach here is to declare the members internal and make sure MyClass and MyObject are part of the same assembly. That assembly should contain little else.
Additional: This is the tool that was designed for this purpose. Other languages have other means to fine-tune accessibility (C++: friend) but in .NET a simpler model was chosen.
And you don't have to take the 'nothing else' so strictly, the 2 classes could share an assembly with other related classes. you would then have to verify the no-access rule(s) manually inside that library.
I'd suggest a private nested class. That way, even if your fellow devs are writing code in the same namespace, they'll never be able to access the class.
Once the class declaration is fully enclosed within another class declaration, the class is considered nested and can only be accessed through the containing class.
Pehaps your MyObject should descend from MyClass and declare the methods in MyClas as protected.
If you don't want your consumers to invoke certain implementation specific methods you could try abstracting to interfaces or abstract base classes. That way the consumer will only 'see' the properties and methods you want them to see.
You do not have to use inheritance to provide shared functionality and you do not have to rely on member accesibility to prevent others from using methods you'd rather not expose.
For example:
public interface IDomainSpecific
{
void DoStuff();
}
public interface IDomainService
{
void HelpMeDoStuff();
}
public class DomainObject1 : IDomainSpecific
{
private readonly IDomainService _service;
public DomainObject1( IDomainService service )
{
_service = service;
}
public DoStuff()
{
// Do domain specific stuff here
// and use the service to help
_service.HelpMeDoStuff();
}
}
This uses classic constructor injection and works best when you already use dependency injection in your application, though it works perfectly well with factories as well.
The point is to keep responsibilities crystal clear. There's no chance of anybody invoking anything they shouldn't because the 'DomainObject' never knows what concrete type implements the shared service. The shared service is not exposed on the domain object either. The added bonus is testability and the possibility of swapping the service with another implementation without ever needing to touch the DomainObject.

Categories

Resources