简体   繁体   English

C# 非相关类型的运行时延迟绑定

[英]C# runtime late binding on non correlated types

I've been asked to port a NetFramework/Ef6 assembly to NetCore / EFCore.我被要求将 NetFramework/Ef6 程序集移植到 NetCore/EFCore。 The migration must be split into small chunks and spread over multiple deploys so it can be tested by QA over time.迁移必须分成小块并分布在多个部署中,以便 QA 可以随着时间的推移对其进行测试。

My idea is to couple all of the logic to a shared type IContext and to return at runtime the EF6 context in the old assembly and the EFCore context in the NetCore assembly so the team can gradually migrate individual services (logic) to the new runtime with minimal effort.我的想法是将所有逻辑耦合到共享类型 IContext 并在运行时返回旧程序集中的 EF6 上下文和 NetCore 程序集中的 EFCore 上下文,以便团队可以逐渐将单个服务(逻辑)迁移到新的运行时最小的努力。

Since there's no common ancestor between the two contexts I was hoping to allow my code to use late binding to call functions on the instances I dynamically resolve in each assembly:由于这两个上下文之间没有共同的祖先,我希望允许我的代码使用后期绑定来调用我在每个程序集中动态解析的实例上的函数:

TypeA a = new TypeA();

a = (dynamic) new TypeB();

a.Log();


public class TypeA
{
    public void Log()
    {
        Console.WriteLine("TypeA");
    }
}

public class TypeB
{
    public void Log()
    {
        Console.WriteLine("TypeB");
    }
}

This throws RuntimeBinderException: Cannot implicitly convert type 'TypeB' to 'TypeA'这会抛出 RuntimeBinderException:无法将类型“TypeB”隐式转换为“TypeA”

Is there any solution to allow such behavior?有什么解决方案可以允许这种行为吗?

Try this.尝试这个。

dynamic a = new TypeA();
a = new TypeB();
a.Log();

If you plan to use multiple assembly load contexts this post may help you.如果您计划使用多个程序集加载上下文,这篇文章可能会对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM