我试图为我的项目构建一个很好的架构,我决定使用Ninject作为DI和Castle project dinamic proxy来为我的存储库添加缓存。不幸的是我得到了一个例外。这是我的代码:
public class NinjectImplementation : NinjectModule
{
public override void Load()
{
// Binding repositories
var assembly = Assembly.GetAssembly(typeof(UserRepository));
var types = assembly.GetTypes()
.Where(t => t.Name.EndsWith("Repository") && !t.Name.StartsWith("I"));
ProxyGenerator generator = new ProxyGenerator();
//CacheInterceptor cacheInterceptor =
foreach (var type in types)
{
var interfaceType = type.GetInterfaces().Single();
var typeWithCaching = generator.CreateClassProxy(type, new MyTestShop.Infrastructure.Caching.CacheInterceptor());
Bind(interfaceType).To(typeWithCaching.GetType()).InThreadScope();
}
...//Service layer injection
}
}因此,我不是注入存储库的实现,而是注入存储库的代理类(带有缓存)。
下面是我的IInterceptor Castle dinamic proxy实现
[Serializable]
public class CacheInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
int argumentCount = invocation.Arguments.Length;
if (argumentCount > 1)
{
invocation.Proceed();
return;
}
String methodNameInLower = invocation.Method.Name.ToLower();
if (methodNameInLower.StartsWith("get"))
{
String cachePath = invocation.TargetType.FullName + "_" + invocation.Method.Name + "_" + invocation.Arguments[0].ToString();
CacheHelper.Get(cachePath);
//DO SOMETHING
return;
}
}
}我在_kernel.Get<T>()方法Ninject DI container中得到的异常
激活路径: 3)将依赖IInterceptor注入到UserRepositoryProxy类型构造函数的参数中;2)在UserService 1型构造函数的参数userRepository中注入依赖IUserRepository
建议: 1)确保提供者正确处理创建请求。
描述:在执行当前web请求时发生了未处理的异常。请查看堆栈跟踪以获得有关错误的更多信息,以及它起源于代码的位置。
异常详细信息: Ninject.ActivationException:使用IInterceptor提供程序的条件隐式自绑定激活IInterceptor的错误返回null。激活路径: 3)将依赖IInterceptor注入到UserRepositoryProxy类型构造函数的参数中;2)在UserService 1型构造函数的参数userRepository中注入依赖IUserRepository
建议: 1)确保提供者正确处理创建请求。
发布于 2013-03-26 08:50:01
我终于找到了我的问题的答案。问题是,我的代理不是类型,而是类型的实例,所以我按如下方式修正了它:
var interfaceType = type.GetInterfaces().Single();
var proxy = generator.CreateClassProxy(type,
new Type[] { interfaceType },
new IInterceptor[]
{
new CacheInterceptor(),
new LoggingInterceptor()
});
// I'm using directive ToConstant(..), and not To(..)
Bind(interfaceType).ToConstant(proxy).InThreadScope();https://stackoverflow.com/questions/15472515
复制相似问题