2

我的程序通过 Win32API 函数与操作系统进行大量交互。现在我想将我的程序迁移到Linux下的Mono下运行(没有wine),这需要不同的实现来与操作系统的交互。

我开始设计一个代码,它可以针对不同的平台有不同的实现,并且可以为新的未来平台扩展。

public interface ISomeInterface
{
    void SomePlatformSpecificOperation();
}

[PlatformSpecific(PlatformID.Unix)]
public class SomeImplementation : ISomeInterface
{
    #region ISomeInterface Members

    public void SomePlatformSpecificOperation()
    {
        Console.WriteLine("From SomeImplementation");
    }

    #endregion
}

public class PlatformSpecificAttribute : Attribute
{
    private PlatformID _platform;

    public PlatformSpecificAttribute(PlatformID platform)
    {
        _platform = platform;
    }

    public PlatformID Platform
    {
        get { return _platform; }
    }
}

public static class PlatformSpecificUtils
{
    public static IEnumerable<Type> GetImplementationTypes<T>()
    {
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (typeof(T).IsAssignableFrom(type) && type != typeof(T) && IsPlatformMatch(type))
                {
                    yield return type;
                }
            }
        }
    }

    private static bool IsPlatformMatch(Type type)
    {
        return GetPlatforms(type).Any(platform => platform == Environment.OSVersion.Platform);
    }

    private static IEnumerable<PlatformID> GetPlatforms(Type type)
    {
        return type.GetCustomAttributes(typeof(PlatformSpecificAttribute), false)
            .Select(obj => ((PlatformSpecificAttribute)obj).Platform);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Type first = PlatformSpecificUtils.GetImplementationTypes<ISomeInterface>().FirstOrDefault();
    }
}

我看到这个设计有两个问题:

  1. 我不能强制ISomeInterface实现PlatformSpecificAttribute.
  2. 多个实现可以用相同的标记PlatformID,我不知道在 Main.js 中使用哪个。使用第一个是 ummm 丑陋的。

如何解决这些问题?你能推荐另一种设计吗?

4

3 回答 3

2

看看 Banshee 的来源。他们有一种巧妙的方式来根据平台插入不同的实现。

于 2010-05-21T13:42:05.807 回答
0

我认为您可以准备两个或多个 app.config 文件,然后在每个文件中相应地注入平台相关的实现。

最后,将繁重的任务留给平台相关的安装或任何其他部署方法,在 Windows 上使用 app.config 的 Windows 版本,而在 Unix 上使用 Unix 版本。

您可以使用插件架构或其他复杂的解决方案来实现其他不错的功能。

于 2010-05-19T11:54:43.010 回答
0

有趣的是,您提到 Unity,您是否考虑过使用依赖注入容器?我相信 Castle Windsor、StructureMap 和 ninject 都可能有一定程度的 Mono 支持。

于 2010-05-19T12:03:05.470 回答