Dynamic Proxy与.NET Core依赖注入的集成
作者:互联网
在《Castle DynamicProxy基本用法》中介绍了如何将DP与Autofac集成使用,而 .NET Core有自己的依赖注入容器,在不依赖第三方容器的基础上,如何实现动态代理就成了一个问题。
.NET Core依赖注入实现动态代理
我们知道,要创建一个代理对象,需要简单的三步:
- 创建Target
- 创建Interceptor
- 使用Target和Interceptor创建代理对象
.NET Core的依赖注入允许我们自定义ServiceDescriptor对象,而在ServiceDescriptor对象中,我们可以定义对象实例化的过程,这个过程叫做factory,通过自定义factory,我们可以类型的动态代理的创建。
代码如下:
services.AddTransient<LoggingInterceptor>();
services.AddTransient<SampleService>();
services.AddTransient<ISampleService>(provider =>
{
var target = provider.GetService<SampleService>();
var loggingInterceptor = provider.GetService<LoggingInterceptor>();
var proxy = DynamicProxyExtensions.Generator.CreateInterfaceProxyWithTarget<ISampleService>(target, loggingInterceptor);
return proxy;
});
或者通过实例化ServiceDescriptor的方式进行注入:
services.AddTransient<LoggingInterceptor>();
services.AddTransient<SampleService>();
Func<IServiceProvider, object> factory = (provider) => {
var target = provider.GetService<SampleService>();
var loggingInterceptor = provider.GetService<LoggingInterceptor>();
var auditInterceptor = provider.GetService<AuditInterceptor>().ToInterceptor();
var proxy = DynamicProxyExtensions.Generator.CreateInterfaceProxyWithTarget<ISampleService>(target, loggingInterceptor, auditInterceptor);
return proxy;
};
var serviceDescriptor = new ServiceDescriptor(typeof(ISampleService), factory, ServiceLifetime.Transient);
services.Add(serviceDescriptor);
通过这种方式,我们可以将动态代理与依赖注入结合起来。但是这样的代码缺少封装,开发效率偏低,在使用过程中还需要对依赖注入、动态代理都有一定了解,为了解决这些问题,我们需要再次封装。
依赖注入与动态代理的简单封装
public static class DependencyInjectionExtensions
{
public static IServiceCollection AddService<TService, TImplementation>(this IServiceCollection services,
ServiceLifetime lifetime, params Type[] interceptorTypes)
{
return services.AddService(typeof(TService), typeof(TImplementation), lifetime, interceptorTypes);
}
public static IServiceCollection AddService(this IServiceCollection services, Type serviceType, Type implType,
ServiceLifetime lifetime, params Type[] interceptorTypes)
{
services.Add(new ServiceDescriptor(implType, implType, lifetime));
Func<IServiceProvider, object> factory = (provider) =>
{
var target = provider.GetService(implType);
List<IInterceptor> interceptors = interceptorTypes.ToList().ConvertAll<IInterceptor>(interceptorType =>
{
return provider.GetService(interceptorType) as IInterceptor;
});
var proxy = DynamicProxyExtensions.Generator.CreateInterfaceProxyWithTarget(serviceType, target, interceptors.ToArray());
return proxy;
};
var serviceDescriptor = new ServiceDescriptor(serviceType, factory, lifetime);
services.Add(serviceDescriptor);
return services;
}
}
在使用时需要注意,一定要先将Interceptor类注入到容器中。
标签:Core,return,Dynamic,factory,GetService,var,Proxy,provider,services 来源: https://www.cnblogs.com/youring2/p/11253116.html