"Niki Estner" <ni*********@cu be.net> wrote in
news:ug******** ******@TK2MSFTN GP15.phx.gbl...
"Bjarke Lindberg" <bv**@thisisjun k.beverli.net> wrote in
news:Oi******** ******@TK2MSFTN GP09.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 RemotingService s.
Niki
using System;
using System.Reflecti on;
using System.Runtime. Remoting;
using System.Runtime. Remoting.Proxie s;
using System.Security .Permissions;
[AttributeUsage( AttributeTarget s.Class)]
[SecurityPermiss ionAttribute(Se curityAction.De mand,
Flags=SecurityP ermissionFlag.I nfrastructure)]
public class MyProxyAttribut e : ProxyAttribute
{
public override MarshalByRefObj ect CreateInstance( Type serverType)
{
if (serverType == typeof(CustomSe rver))
{
DerivedClass d = new DerivedClass();
return d;
}
else
{
MethodInfo mi =
typeof(Remoting Services).GetMe thod("AllocateI nitializedObjec t",
BindingFlags.St atic|BindingFla gs.NonPublic, null, new Type[] {
typeof(Type) }, null);
object o = mi.Invoke(null, new object[] { typeof(DerivedC lass) });
return (MarshalByRefOb ject)o;
}
}
}
[MyProxyAttribut e]
public class CustomServer : ContextBoundObj ect
{
public virtual void HelloMethod()
{
Console.WriteLi ne("Base method");
}
}
public class DerivedClass : CustomServer
{
public override void HelloMethod()
{
Console.WriteLi ne("Been derived!");
}
}
class Test
{
static unsafe void Main()
{
CustomServer x = new CustomServer();
x.HelloMethod() ;
}
}