我试图为我的项目构建漂亮的架构,我决定使用 Ninject
作为 DI 和 Castle project
dinamic proxy
为我的存储库添加缓存。不幸的是我得到一个异常(exception)。这是我的代码:
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
}
}
所以我注入(inject)的不是存储库的实现,而是存储库的代理类(带缓存)。
这是我的 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
的方法| :
- Error activating IInterceptor using conditional implicit self-binding of IInterceptor Provider returned null.*
Activation path: 3) Injection of dependency IInterceptor into parameter of constructor of type UserRepositoryProxy 2) Injection of dependency IUserRepository into parameter userRepository of constructor of type UserService 1) Request for IUserService
Suggestions: 1) Ensure that the provider handles creation requests properly.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Ninject.ActivationException: Error activating IInterceptor using conditional implicit self-binding of IInterceptor Provider returned null. Activation path: 3) Injection of dependency IInterceptor into parameter of constructor of type UserRepositoryProxy 2) Injection of dependency IUserRepository into parameter userRepository of constructor of type UserService 1) Request for IUserService
Suggestions: 1) Ensure that the provider handles creation requests properly.
最佳答案
我终于找到了问题的答案。问题是我的代理不是类型而是类型的实例所以我这样修复它:
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();
关于c# - CaSTLe 动态代理 + Ninject as DI 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15472515/