C# 为什么';t为接口使用触发模块初始值设定项 代码
所以我有两个集会 “AssemblyWithClassAndModuleInit”包含一个类C# 为什么';t为接口使用触发模块初始值设定项 代码,c#,.net,C#,.net,所以我有两个集会 “AssemblyWithClassAndModuleInit”包含一个类 public class MyBaseClass { } “AssemblyWithInterfaceAndModuleInit”包含一个接口 public interface MyInterface { } 两者都包含一个模块初始值设定项 public static class ModuleInitializer { public static void Initialize()
public class MyBaseClass
{
}
“AssemblyWithInterfaceAndModuleInit”包含一个接口
public interface MyInterface
{
}
两者都包含一个模块初始值设定项
public static class ModuleInitializer
{
public static void Initialize()
{
Environment.SetEnvironmentVariable("ModuleInitializer", "true");
}
}
“AssemblyWithClassAndModuleInit”的测试(注意MyBaseClass
用作ClassTests
的基础)
测试“AssemblyWithInterfaceAndModuleInit”(注意MyInterface
用作InterfaceTests
的接口)
唯一失败的测试是接口测试。确保调用RemomoduleInit
问题
为什么会这样?InterfaceTests
实现了MyInterface
这一事实不应该导致模块初始值设定项运行吗
如何注入模块初始值设定项
我正在使用IL编织。具体地
它检测到了这一点
public static class ModuleInitializer
{
public static void Initialize()
{
//Init code
}
}
并补充说
static <Module>()
{
ModuleInitializer.Initialize();
}
static()
{
ModuleInitializer.Initialize();
}
更新
- 如果我添加了一个字段
到typeinterfacetype=typeof(MyInterface),则作为旁白
然后所有测试都通过接口测试
- 编码是针对.NET4.5进行的
这里有一个单元测试的repo一个明显的潜在关联:测试类派生自prod程序集中的基类。因此,创建测试类的实例需要调用基类中的构造函数(隐式),这意味着基类需要完全加载和初始化,因此程序集需要初始化 与您的接口版本相比,您在测试类中实现prod assembly接口的事实在执行时实际上是无关紧要的,因为您没有做任何需要该接口的事情 我怀疑如果你有:
public void Foo(MyInterface x)
{
}
[Test]
public void EnsureAssemblyIsLoaded()
{
Foo(this);
... assertions ...
}
然后可以初始化程序集。如果在接口中声明了任何方法,并且从
Foo
调用了其中一个方法,然后我肯定希望程序集被初始化。提到您使用的CLR版本可能很重要。您的问题根本没有提到Fody-大概这就是模块初始化器类做任何事情的魔力吧?(否则,我不清楚是什么做的…)这个例子有点混乱。也许最好这样做:var ifacetype=typeof(MyInterface);断言。相等(“真”等);这更清楚地表明,当您第一次使用一种类型的模块时,您希望模块初始值设定项能够运行。@JonSkeet yep注入模块init的是Fody。我有最新消息question@GeertvanHorrik有趣的是,如果我向InterfaceTests添加一个字段“typeInterfaceType=typeof(MyInterface);”,那么所有测试都通过了
static <Module>()
{
ModuleInitializer.Initialize();
}
public void Foo(MyInterface x)
{
}
[Test]
public void EnsureAssemblyIsLoaded()
{
Foo(this);
... assertions ...
}