استفاده از AOP Interceptorها در برنامههای NET Core. با استفاده از IoC Container توکار
اگر بخواهیم Container مثال مطلب جاری را با IoC Container توکار NET Core. تعویض کنیم به کدهای زیر خواهیم رسید:
var descriptors = services.ToList();
var proxyGenerator = new ProxyGenerator();
foreach (var descriptor in descriptors)
{
var serviceInterfaceType = descriptor.ServiceType;
services.Replace(ServiceDescriptor.Describe(descriptor.ServiceType,
provider => proxyGenerator.CreateInterfaceProxyWithTargetInterface(descriptor.ServiceType,
provider.GetInstance(descriptor),
new LoggingInterceptor()),
descriptor.Lifetime));
}
با پیمایش لیست ServiceDescriptorهای رجیستر شده در Container، به ازای تک تک سرویسهای موجود، کار تعویض Descriptor متناظر با آن را انجام میدهیم. برای این منظور یک implementationFactory را با استفاده از ProxyGenerator به شکل زیر میتوان ایجاد کرد:
provider => proxyGenerator.CreateInterfaceProxyWithTargetInterface(descriptor.ServiceType,
provider.GetInstance(descriptor),
new LoggingInterceptor())
در اینجا برای مهیا کردن شی target مورد نیاز ProxyGenerator، از متد الحاقی provider.GetInstance استفاده شده است که به شکل زیر پیاده سازی شده است:
public static object GetInstance(this IServiceProvider provider, ServiceDescriptor descriptor)
{
if (descriptor.ImplementationInstance != null)
{
return descriptor.ImplementationInstance;
}
if (descriptor.ImplementationType != null)
{
return provider.GetServiceOrCreateInstance(descriptor.ImplementationType);
}
return descriptor.ImplementationFactory(provider);
}
private static object GetServiceOrCreateInstance(this IServiceProvider provider, Type type)
{
return ActivatorUtilities.GetServiceOrCreateInstance(provider, type);
}
در تکه کد بالا، با بررسی ImplementationInstance، ImplementationType و ImplementationFactory متناظر با ServiceDescriptor مورد نظر، کار دریافت یا ایجاد وهلهی
متناظر با ServiceType انجام میشود.