在程序集

时间:2015-06-05 15:15:25

标签: c# .net dynamic reflection .net-assembly

可能我要问的是不可能的,但不过这是我的问题和疑问。首先,这是C#和.NET 我想以这种方式将类的空实现(空方法,函数返回默认值)定义为接口,如果我更改接口,则不需要调整代码。不幸的是我无法生成包含程序集的实现,我无法在其上定义动态模拟,因为实例化是通过反射自动完成的。以下是更广泛解释的问题:

我有一个dll /程序集让我们称它为IMyInterface.dll,其中包含一个接口:IMyInterface。
上面的图层我在一个单独的dll /程序集中实现了让我们称之为MyInterfaceImplementation.dll 在中间/之间我有一个自动化的测试框架,它可以依赖于IMyInterface.dll但不依赖于MyInterfaceImplementation.dll。
现在,此测试框架使用通过反射实例化类型的生产代码基础结构。它是一个依赖注入类型框架。 所以你对生产代码基础设施说,从这个程序集给我这个接口实现 在我们的例子中,你说从MyInterfaceImplementation.dll给我一个IMyInterface。 在测试框架中,您不能依赖于MyInterfaceImplementation,因此您在第三个程序集中定义基于IMyInterface的伪/存根/模拟类,我们可以调用它:MyInterfaceFakeImplementation.dll
在测试框架中,你说从MyInterfaceFakeImplementation.dll给我一个IMyInterface,你没事。
注意:对我们的模块层次结构执行操作时,无法重构依赖项。关于模拟框架,我不控制实例化。实例化在依赖注入框架内完成。

当你在MyInterfaceFakeImplementation.dll中编写代码时,你会写下这样的代码:

class MyInterfaceFakeImplementation : IMyInterface 
{
  // IMyInterface implementation. 
}

现在我想提供的是IMyInterface的动态类,所以当界面改变时我不需要调整假。

这里很简短就是我想要的:

鉴于


IMyInterface.dll中的IMyInterface接口
MyInterfaceFakeImplementation.dll中的IMInInterface的MyInterfaceFakeImplementation实现 MyInterfaceFakeImplementation具有空函数并返回默认值。

当:
我更改了IMyInterface(例如,更改函数签名)。

然后:
我不需要更改MyInterfaceFakeImplementation,只需重新编译MyInterfaceFakeImplementation.dll。注意:无法生成此程序集,需要进行编译。

这是一种解决方法 在IMyInterface.dll中的IMyInterface旁边执行一个假实现(类),让我们称之为MyInterfaceFakeBase。 在MyInterfaceFakeImplementation.dll中从此基类MyInterfaceFakeBase派生MyInterfaceFakeImplementation并将其保留为空。 更改界面(IMyInterface)时,请调整MyInterfaceFakeBase,不要担心MyInterfaceFakeImplementation和MyInterfaceFakeImplementation.dll。

Okie,对于那些想要开始编码的人来说,这是一个示例控制台类型的应用程序,可能会有所帮助。在此代码中添加一个类,以便找到实现该接口的类型,如果更改了该接口,则无需更改该类。 (不要修改主要功能。)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DynamicFake3
{
    public interface IMyInterface
    {
        void SimpleMethod();
        bool SimpleFunction();
        void OneParameterMethod(int i);
    }

    class Program
    {
        static void Main(string[] args)
        {

            Assembly anAssembly = Assembly.LoadFrom("DynamicFake3.exe");

            foreach (Type aType in anAssembly.GetTypes())
            {
                if (aType.GetInterfaces().Contains(typeof(IMyInterface)))
                {
                    Console.WriteLine(aType.FullName);
                }
            }
        }
    }
}

再见 的Laszlo

2 个答案:

答案 0 :(得分:0)

没有人回答,所以不可能这样做。 可以在运行时期间为接口创建动态装饰器或代理或模拟,或者生成具有接口的伪实现的程序集,但不是我想要的。 C#,.NET,CLR不允许它。或者更好地说,C#不允许这种动态(解释)行为是一件好事。

答案 1 :(得分:0)

您可以使用类型转发来声明类型移动到运行时生成的程序集(请参阅assemblybuilder),您可以在其中发出类型(请参阅typebuilder)。