The intent of the proxy-pattern is to provide a placeholder for another object to control access to it. It introduces an additional level of indirection. There are several reasons why you would want to do this,
2. What is the Proxy Pattern?
• The intent of the proxy-pattern is to provide a placeholder for another object to
control access to it. It introduces an additional level of indirection. There are
several reasons why you would want to do this,
• defer the full cost of its creation and initialization until we actually need to
use it.
• A remote proxy is responsible for encoding a request and its arguments and for
sending (and retrieving) the request (and the response) to the real object.
• A virtual proxy may cache additional information about the real subject so that
it can postpone the access to it.
• A protection proxy checks whether the caller has sufficient access permissions
for perform a request.
• In many cases, real world proxies are a combination of some of these basic
proxies
3. What is System.Reflection.DispatchProxy?
• Provides a class to dynamically create proxy types that implement
a specified interface and derive from a specified DispatchProxy
type. Method invocations on the generated proxyinstance are
dispatched to that DispatchProxy base type.
4. How to use Proxy Pattern in C# Core 2
• You will need the package System.Reflection.DispatchProxy
ServiceControllerA
Client Factory
ServiceControllerB
ServiceA
Configuration
Service A
5. My Service : ServiceA
public class ServiceA : IServiceA
{
public string GetName()
{
return "Michel Bruchet";
}
}
6. My two controllers : Controller A and B
public class ControllerA : IServiceA
{
public string GetName()
{
return new ServiceA().GetName();
}
}
7. My two Classes Proxy
public class ClassProxyA : System.Reflection.DispatchProxy
{
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
return new ControllerA().GetName();
}
}
8. My Factory
public IServiceA GetService()
{
if (_type == "A")
return DispatchProxy.Create<IServiceA, ClassProxyA>();
else
return DispatchProxy.Create<IServiceA, ClassProxyB>();
}
}
9. My Client
static void Main(string[] args)
{
var factory = new MyClassFactory("A");
var name = factory.GetName();
Console.Write($"hello {name}");
}