"Niki Estner" <ni*********@cube.net> wrote in
news:ug**************@TK2MSFTNGP15.phx.gbl...
"Bjarke Lindberg" <bv**@thisisjunk.beverli.net> wrote in
news:Oi**************@TK2MSFTNGP09.phx.gbl... Hey NG.
Using .NET remoting it's possible to "override" the <c>new</c> operator
to return a proxy to the object in question.
I'd like to use this approach to let a factory class return the reference
to the newly created object instead of letting the runtime instantiate
the object.
Does anybody know any references for doing this? (If it's possible at
all). Any feedback would be appriciated.
Can you apply a custom attribute to that class? Then it's quite easy (see
code below).
The code I posted before always returned a transparent proxy; The only way
I've found to create the real object without a proxy was using an
undocumented function from RemotingServices.
Niki
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Proxies;
using System.Security.Permissions;
[AttributeUsage(AttributeTargets.Class)]
[SecurityPermissionAttribute(SecurityAction.Demand,
Flags=SecurityPermissionFlag.Infrastructure)]
public class MyProxyAttribute : ProxyAttribute
{
public override MarshalByRefObject CreateInstance(Type serverType)
{
if (serverType == typeof(CustomServer))
{
DerivedClass d = new DerivedClass();
return d;
}
else
{
MethodInfo mi =
typeof(RemotingServices).GetMethod("AllocateInitia lizedObject",
BindingFlags.Static|BindingFlags.NonPublic, null, new Type[] {
typeof(Type) }, null);
object o = mi.Invoke(null, new object[] { typeof(DerivedClass) });
return (MarshalByRefObject)o;
}
}
}
[MyProxyAttribute]
public class CustomServer : ContextBoundObject
{
public virtual void HelloMethod()
{
Console.WriteLine("Base method");
}
}
public class DerivedClass : CustomServer
{
public override void HelloMethod()
{
Console.WriteLine("Been derived!");
}
}
class Test
{
static unsafe void Main()
{
CustomServer x = new CustomServer();
x.HelloMethod();
}
}