c# - CaSTLe 动态代理 + Ninject as DI 的问题

标签 c# .net dependency-injection ninject castle-dynamicproxy

我试图为我的项目构建漂亮的架构,我决定使用 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/

相关文章:

c# - 如何将变量传递给另一个场景中的脚本

c# - 将数据作为原始数据传递给打印机

dependency-injection - 为什么 Simple Injector 没有像 Unity 这样的 IContainer 抽象?

c# - 使用方法但没有字段或属性的类实例化有多快?

c# - 从字符串到 bool 值的奇怪映射行为

c# - 是否有用于 C# 的 XML 文字加载项可以将 XML 文字转换为 C# 对象?

c# - 在控制台应用程序中使用连字符命名输入的简单方法是什么(即 -S "myServerName")?

c# - 在 C# 中捕获 MySQL 触发信号

java - 看不懂字段注入(inject)

c# - 是否可以在我的 aspx View 中使用 'using' 语句? (ASP.NET MVC)