It looks like RealProxy won't come to .NET Core/Standard। इस मुद्दे में, एक माइक्रोसॉफ्ट डेवलपर एक विकल्प के रूप में DispatchProxy सुझाता है।
इसके अलावा, कुछ मौजूदा एओपी ढांचे पहले से या भविष्य में .NET कोर का समर्थन कर सकते हैं (जैसा कि प्रश्न पर टिप्पणियों में देखा गया है)।
एक विकल्प DispatchProxy
है, जिसमें यहां एक शानदार उदाहरण है: http://www.c-sharpcorner.com/article/aspect-oriented-programming-in-c-sharp-using-dispatchproxy/।
public class LoggingDecorator<T> : DispatchProxy
{
private T _decorated;
protected override object Invoke(MethodInfo targetMethod, object[] args)
{
try
{
LogBefore(targetMethod, args);
var result = targetMethod.Invoke(_decorated, args);
LogAfter(targetMethod, args, result);
return result;
}
catch (Exception ex) when (ex is TargetInvocationException)
{
LogException(ex.InnerException ?? ex, targetMethod);
throw ex.InnerException ?? ex;
}
}
public static T Create(T decorated)
{
object proxy = Create<T, LoggingDecorator<T>>();
((LoggingDecorator<T>)proxy).SetParameters(decorated);
return (T)proxy;
}
private void SetParameters(T decorated)
{
if (decorated == null)
{
throw new ArgumentNullException(nameof(decorated));
}
_decorated = decorated;
}
private void LogException(Exception exception, MethodInfo methodInfo = null)
{
Console.WriteLine($"Class {_decorated.GetType().FullName}, Method {methodInfo.Name} threw exception:\n{exception}");
}
private void LogAfter(MethodInfo methodInfo, object[] args, object result)
{
Console.WriteLine($"Class {_decorated.GetType().FullName}, Method {methodInfo.Name} executed, Output: {result}");
}
private void LogBefore(MethodInfo methodInfo, object[] args)
{
Console.WriteLine($"Class {_decorated.GetType().FullName}, Method {methodInfo.Name} is executing");
}
}
तो अगर हम एक इसी इंटरफेस (यहाँ नहीं दिखाया गया है) के साथ एक उदाहरण वर्ग Calculator
है:
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
}
हम कर सकते हैं
हम कोड को आसान बनाने में है, तो यह है कि हम क्या मिलता है बस इस
static void Main(string[] args)
{
var decoratedCalculator = LoggingDecorator<ICalculator>.Create(new Calculator());
decoratedCalculator.Add(3, 5);
Console.ReadKey();
}
क्या आपको इसका समाधान मिला ??? –
@RafaelEnriquez आज तक एएसपी नेट कोर में लागू नहीं किया गया है 1. शायद 1.1 या 1.2 के साथ। जब मुझे कुछ मिला तो मैं यहां उत्तर पोस्ट करूंगा :) –
तो इसका समाधान क्या है? https://www.nuget.org/packages/System.Runtime/ .NetCore के साथ संगत है? –