lok*_*oki 1 c# oop aop design-patterns postsharp
我想使用 AOP 来处理控制台应用程序中的错误异常。(这不是 MVC,我使用属性花瓶编程来处理 MVC 中的错误,但这是控制台应用程序)我的代码如下:(如果发生错误,它应该在我的属性端代码中抛出错误)
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleError : Attribute
{
public HandleError(string description)
{
try
{
this.Description = description;
}
catch (Exception)
{
throw;
}
}
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这将从我的方法中调用:
[HandleError("Error occurs here")]
public static void MyMethod(string data)
{
throw new Exception();
Run Code Online (Sandbox Code Playgroud)
实际上; 我想使用 AOP 来处理我的方法内的异常。如果发生错误,我必须调用属性。但如何呢?(请不要提供 postsharp,它需要钱。但我也开放开源)顺便说一句;为什么这不容易,我不明白。
基本上,PostSharp 所做的就是在编译时将代码编织到程序集中,该程序集在用属性标记的方法之前和之后运行。从性能的角度来看,这非常好,因为没有使用在运行时动态创建的代码。
其他一些 AOP 框架(或 IoC 容器)提供了生成动态代理的选项,其中包含在运行时拦截对方法的调用的代码。
要么使用这些框架之一(寻找 IoC 和拦截),要么自己实现类似的功能。基本上你要做的就是将你想要拦截的代码移动到一个类中并将方法标记为virtual. 在运行时,您可以使用动态创建的类来装饰该类的实例,该类继承自您的类并重写方法,以便在调用该方法之前和之后运行附加代码。
但是,可能有一种更简单的方法可以满足控制台应用程序的需求。您还可以创建一些辅助函数,其中包含要在方法之前和之后运行的代码,而不是使用属性标记方法:
void Main()
{
int value = GetValue(123);
DoSomething(value);
}
void DoSomething(int myParam)
{
RunAndLogError(() => {
// Place code here
Console.WriteLine(myParam);
});
}
int GetValue(int myParam)
{
return RunAndLogError(() => {
// Place code here
return myParam * 2;});
}
void RunAndLogError(Action act)
{
try
{
act();
}
catch(Exception ex)
{
// Log error
throw;
}
}
T RunAndLogError<T>(Func<T> fct)
{
try
{
return fct();
}
catch(Exception ex)
{
// Log error
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,RunAndLogError 有两种重载,一种用于 void 方法,另一种用于返回值的方法。
另一种选择是使用全局异常处理程序来实现此目的;有关详细信息,请参阅此答案:.NET Global exception handler in console application
| 归档时间: |
|
| 查看次数: |
1906 次 |
| 最近记录: |