我正在使用Asp.Net Core 2和Castle Core。
我使用如下所示的拦截方法创建了一个名为ConfigurationInterceptor
的自定义拦截器:
public void Intercept(IInvocation invocation)
{
var bwinAccessId = _httpContextAccessor.HttpContext.Request.Headers["accessId"];
if (bwinAccessId.IsNullOrEmpty())
{
throw new Exception("AccessId can not be empty in the headers");
}
var accessInfo = _accessInfoStore.GetAccessInfoByIdentifier(bwinAccessId);
var config = _configProvider.GetConfiguration<T, TImpl>(accessInfo, _configurationInfo.FeatureName);
var func = _accessors.GetOrAdd(invocation.Method, CompileToFunc);
invocation.ReturnValue = func(config, invocation.Arguments);
}
我创建了一个扩展方法来注册一些服务,如下所示:
internal static void AddSingletonConfiguration<TInterface, TImplementation>(this IServiceCollection services,
string featureName, Func<ConfigurationInfo<TImplementation>, IConfigurationInterceptor<TInterface, TImplementation>> ic)
where TImplementation : class, TInterface
where TInterface : class
{
var info = new ConfigurationInfo<TImplementation>(featureName, typeof(TInterface));
var generator = new ProxyGenerator();
services.AddSingleton(x =>
{
var icTemp = ic.Invoke(info);
return (TInterface)generator.CreateInterfaceProxyWithoutTarget(info.ServiceType, icTemp);
});
}
在启动时,我这样注册:
services.AddSingletonConfiguration<IStaticDataConfiguration, StaticDataConfiguration>(
"SomeKey",
x => GetConfigurationInterceptor<IStaticDataConfiguration, StaticDataConfiguration>(
new ConfigurationInfo<IStaticDataConfiguration>(x.FeatureName, x.ServiceType)));
上面的 GetConfigurationInterceptor
方法返回了我的自定义拦截器。
稍后,当我尝试使用IStaticDataConfiguration
时,它可以正常工作,但是我唯一的问题是该服务仅包含属性,而我无法传递一些参数。就我而言,我需要bwinAccessId
的Intercept方法。我可以从标头中获取它,但是我在考虑使用proptis而不是方法时是否存在传递参数的理想方法?