如何使用`Ninject.Extensions.Factory`为内部类动态生成工厂?

时间:2015-02-06 22:37:59

标签: ninject factory internal castle-dynamicproxy ninject-extensions

我需要使用Ninject.Extensions.Factory来生成内部类的构造函数。举个例子:

using Ninject.Extensions.Conventions;
using Ninject.Modules;
using Ninject.Extensions.Factory;

namespace ClassLibrary
{
    using System;

    namespace ClassLibrary
    {
        internal class Class1
        {
            public void Print(string message)
            {
                Console.WriteLine(message);
            }
        }

        internal interface IClass1Factory
        {
            Class1 Create();
        }

        public interface IInterface2
        {
            void PrintMessage();
        }
        internal class Class2 : IInterface2
        {
            private readonly IClass1Factory _class1Factory;

            public Class2(IClass1Factory class1Factory)
            {
                _class1Factory = class1Factory;
            }

            public void PrintMessage()
            {
                Class1 class1 = _class1Factory.Create();
                class1.Print("Class2's IInterface2 'PrintMessage' implementation.");
            }
        }

        public class MyNinjectModule : NinjectModule
        {
            public override void Load()
            {
                Kernel.Bind(r => r
                .FromThisAssembly()
                .IncludingNonePublicTypes()
                .SelectAllClasses()
                .BindAllInterfaces());

                Kernel.Bind<IClass1Factory>().ToFactory();
            }
        }
    }
}

使用该库的应用程序:

using ClassLibrary.ClassLibrary;
using Ninject;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel();
            kernel.Load<MyNinjectModule>();
            IInterface2 interface2 = kernel.Get<IInterface2>();
            interface2.PrintMessage();
        }
    }
}

即使在包含[assembly: InternalsVisibleTo(InternalsVisible.ToDynamicProxyGenAssembly2)]之后,我收到以下运行时错误:

  

{“从程序集中键入'Castle.Proxies.IClass1FactoryProxy'   'DynamicProxyGenAssembly2,Version = 0.0.0.0,Culture = neutral,   PublicKeyToken = null'正在尝试实现无法访问   接口 “:”“}

知道如何解决这个问题吗?

0 个答案:

没有答案