现在我正在使用StructureMap4注册表中带有IFormsAuthenticationProvider
的Castle生成的代理来装饰我的 StructureMap4 映射类型,例如tryCatchInterceptor
。例如:
public class AuthenticationRegistry : Registry
{
public AuthenticationRegistry()
{
var proxyGenerator = new ProxyGenerator();
var tryCatchInterceptor = new TryCatchInterceptor();
For<IFormsAuthenticationProvider>().Use<FormsAuthenticationProvider>()
.DecorateWith(x => proxyGenerator.CreateInterfaceProxyWithTarget<IFormsAuthenticationProvider>(x, tryCatchInterceptor));
}
}
public class TryCatchInterceptor : IInterceptor
{..}
但是正如你所看到的,我必须在装饰方法中指定类型。所以,必须为所有IType-&gt; Type定义类似的装饰器,此时代码变得重复。
问题:有没有办法在一个共同的地方做到这一点,所有类型都没有重复?
答案 0 :(得分:0)
创建了一个类模板并动态创建了该类。在编译并运行代码后将类加载到内存中。
<强> classTemplate.txt 强>
using Castle.DynamicProxy;
using StructureMap;
using System.Web;
using Company1.WebApplication.App1.Meta;
using Company1.WebApplication.App1.Meta.Interceptors;
namespace Company1.WebApplication.App1
{
public class DynamicUtils
{
private static StructureMapDependencyResolver _structureMapResolver { get; set; }
private static ProxyGenerator _ProxyGenerator = new ProxyGenerator();
public static void ConfigureCastleInterceptor(Container container)
{
container.Configure(x =>
{
##INTERFACE##
});
}
}
}
并在我的 Global.asax 中编写了加载它的代码
private static void ConfigureCastleInterceptor(Container container)
{
string classBody = File.ReadAllText(HttpRuntime.AppDomainAppPath + "/RuntimeClasses/RegisterInterceptors.txt");
var classBuilder = new StringBuilder();
string interfaceTemplate = "x.For<##INTERFACE##>()
.DecorateAllWith(y => _ProxyGenerator
.CreateInterfaceProxyWithTarget<##INTERFACE##>(y, new TryCatchLoggingInterceptor())); \n";
foreach (var instance in container.Model.AllInstances)
{
if (instance.PluginType.FullName.Contains("Company1.WebApplication"))
classBuilder.Append(interfaceTemplate.Replace("##INTERFACE##", instance.PluginType.FullName));
}
classBody = classBody.Replace("##INTERFACE##", classBuilder.ToString());
var csharp = new CSharpCodeProvider();
var compiler = new CompilerParameters();
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
compiler.ReferencedAssemblies.Add(asm.Location);
}
compiler.GenerateInMemory = true;
compiler.GenerateExecutable = false;
CompilerResults results = csharp.CompileAssemblyFromSource(compiler, classBody);
if (!results.Errors.HasErrors)
{
Assembly assembly = results.CompiledAssembly;
Type program = assembly.GetType("Company1.WebApplication.App1.DynamicUtils");
MethodInfo configureCastleInterceptor = program.GetMethod("ConfigureCastleInterceptor");
configureCastleInterceptor.Invoke(null, new Object[] { container });
}
else
{
throw new Exception(results.Errors.ToString());
}
}