Я не могу запустить LogAspect с помощью Castle DynamicProxyC#

Место общения программистов C#
Ответить
Anonymous
 Я не могу запустить LogAspect с помощью Castle DynamicProxy

Сообщение Anonymous »

Я использую в проекте структуру Interceptors , созданную с помощью Castle DynamicProxy, и написал LogAspect для регистрации операций. Однако LogAspect никак не запускается. Я делюсь своими кодами ниже. Я жду вашей помощи, в чем может быть проблема или какие изменения мне нужно внести для правильной работы.

Код: Выделить всё

namespace ebordro.Interceptors
{
//kullanılacak tüm interceptionların temel sınıfı
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class MethodInterceptionBaseAttribute : Attribute, IInterceptor
{
public int Priority { get; set; } //verilen sırada çalışması için.

public virtual void Intercept(IInvocation invocation)
{
}
}
}

Код: Выделить всё

namespace ebordro.Interceptors
{
//metotlarlarda kullanılacak olan interception işlemleri için temel sınıf.
public class MethodInterception : MethodInterceptionBaseAttribute
{
protected virtual void OnBefore(IInvocation invocation) { }
protected virtual void OnAfter(IInvocation invocation) { }
protected virtual void OnException(IInvocation invocation, Exception e) { }
protected virtual void OnSuccess(IInvocation invocation) { }

public override void Intercept(IInvocation invocation)
{
var isSuccess = true;
OnBefore(invocation);
try
{
invocation.Proceed();
}
catch (Exception e)
{
isSuccess = false;
OnException(invocation, e);
throw;
}
finally
{
if (isSuccess)
{
OnSuccess(invocation);
}
}

OnAfter(invocation);
}
}

}

Код: Выделить всё

namespace ebordro.Interceptors
{
//hangi interceptor'ların uygulanacağını seçer.
public class AspectInterceptorSelector : IInterceptorSelector
{
public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
{
var classAttributes = type.GetCustomAttributes(true).ToList();
var methodAttributes = type.GetMethod(method.Name).GetCustomAttributes(true);
classAttributes.AddRange(methodAttributes);

return classAttributes.OrderBy(x =>  x.Priority).ToArray();

}
}
}

Код: Выделить всё

namespace ebordro.Interceptors.Aspects
{
public class LogAspect : MethodInterception
{
private readonly IActionLogService _actionLogService;
private readonly IHttpContextAccessor _httpContextAccessor;

public LogAspect()
{
var serviceProvider = ServiceToolForAspect.CreateScope().ServiceProvider;
_actionLogService = serviceProvider.GetRequiredService();
_httpContextAccessor = serviceProvider.GetRequiredService();

}
protected override void OnAfter(IInvocation invocation)
{
using (var scope = ServiceToolForAspect.serviceProvider.CreateScope())
{
var actionLogService = scope.ServiceProvider.GetRequiredService();
using (var scope = ServiceToolForAspect.CreateScope())
{
var actionLogService = scope.ServiceProvider.GetRequiredService();

var httpContextAccessor = scope.ServiceProvider.GetRequiredService();

var httpContext = httpContextAccessor.HttpContext;

string usermail = httpContext.User.Identity.Name;
int userId = 0;
int companyId = 0;

if (httpContext.User.Identity.IsAuthenticated)
{
var userIdClaim = httpContext.User.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
userId = int.Parse(userIdClaim.Value);
}

var companyIdClaim = httpContext.User.FindFirst("CompanyId");
if (companyIdClaim != null)
{
companyId = int.Parse(companyIdClaim.Value);
}
}

İşlem detayını oluştur
var processDetail = CreateProcessDetail(invocation);

Loglama işlemini gerçekleştir
actionLogService.AddLogRecordAsync(userId, usermail, companyId, invocation.Method.Name.ToUpper(), processDetail)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
}
var httpContext = _httpContextAccessor.HttpContext;

var usermail = httpContext.User.Identity.Name;
var userId = 0;
var companyId = 0;

var processDetail = CreateProcessDetail(invocation);

if (httpContext.User.Identity.IsAuthenticated)
{
var userIdClaim = httpContext.User.FindFirst(ClaimTypes.NameIdentifier);
if (userIdClaim != null)
{
userId = int.Parse(userIdClaim.Value);
}

var companyIdClaim = httpContext.User.FindFirst("CompanyId");
if (companyIdClaim != null)
{
companyId = int.Parse(companyIdClaim.Value);
}
}

//_actionLogService.AddLogRecordAsync(userId,usermail,companyId,invocation.Method.Name.ToUpper(),processDetail).Wait();
_actionLogService.AddLogRecordAsync(userId, usermail, companyId, invocation.Method.Name.ToUpper(), processDetail).ConfigureAwait(false).GetAwaiter().GetResult();

}

private string CreateProcessDetail(IInvocation invocation)
{
var methodName = invocation.Method.Name;
var arguments = invocation.Arguments;

string message = $"{methodName} metodu çağrıldı.  Parametreler: ";

for (int i = 0; i < arguments.Length; i++)
{
message += $"Parametre {i + 1}: {arguments[i]?.ToString() ?? "null"}; ";
}

return message;
}

}
}

Код: Выделить всё

[LogAspect]
public async Task AddLogRecordAsync(int userId, string stringValue, int? intValue, string process, string processDetail)
{
...codes...
}

Что я пробовал:
  • Я создал структуру перехвата с помощью Castle DynamicProxy
    Что я пробовал:

    Я создал структуру перехвата с помощью Castle DynamicProxy и определил класс LogAspect для операций регистрации.
  • Я указал LogAspect как атрибут, производный от класса MethodInterceptionBaseAttribute .
    Я собрал атрибуты, присвоенные методам или классы с помощью класса AspectInterceptorSelector и стремились запускать их в указанном порядке.
  • Я решил зависимости, используя контейнер DI с ServiceToolForAspect.
Чего я ожидал:
  • Когда GetAllActionLogAsync метод называется LogAspect вступит в игру и выполнит операции регистрации, запустив OnBefore, OnAfter или другие методы перехвата.
Что произошло на самом деле:
  • Код: Выделить всё

    LogAspect 
    вообще не работает. Методы, похоже, не проходят через перехват. Коды журналирования, которые я написал внутри метода, не работают, и я не получаю никаких сообщений об ошибках.


Подробнее здесь: https://stackoverflow.com/questions/792 ... namicproxy
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»