인터페이스가있는 플러그인 아키텍처; 인터페이스 점검이 작동하지 않습니다

StackOverflow https://stackoverflow.com/questions/1269608

문제

응용 프로그램에서 간단한 플러그인 아키텍처를 구현하고 있습니다. 플러그인 요구 사항은 응용 프로그램 및 플러그인에서 참조되는 a *.dll에있는 인터페이스 (iplugin)를 사용하여 정의됩니다. 애플리케이션에는 플러그인 폴더의 모든 *.dll을 찾아 플러그인을로드하고로드 한 다음 플러그인이 인터페이스를 구현하는지 확인하여 플러그인 관리자 (동일 *.dll)가 있습니다. 이 두 가지 방법을 확인했습니다. 코드는 다음과 같습니다.

Assembly pluginAssembly = Assembly.LoadFrom(currFile.FullName);
if (pluginAssembly != null)
{
    foreach (Type currType in pluginAssembly.GetTypes())
    {
        if (currType.GetInterfaces().Contains(typeof(IPlugin)))
        {
            // Code here is never executing
            // even when the currType derives from IPlugin
        }
    }                    
}

나는 특정 클래스 이름 ( "플러그인")을 테스트했지만 어셈블리의 모든 클래스를 순환 할 수 없었습니다. (이것은 내가 다른 곳에서 찾은 예를 따릅니다.) 이것을 조금 더 복잡하게 만들기 위해, 각각의 인터페이스가 원래 인터페이스 (iplugina, ipluginb)를 구현합니다. 플러그인은 실제로보다 구체적인 인터페이스 중 하나 (ipluginb)를 구현합니다. 그러나 더 일반적인 인터페이스 (iplugin)를 구현하는 플러그인으로 시도했지만 여전히 작동하지 않습니다.

편집 : 내가 처음받은 두 가지 응답에 대한 응답으로] 예, IsAssignableFrom을 사용해 보았습니다. 다음을 참조하십시오.

Assembly pluginAssembly = Assembly.LoadFrom(currFile.FullName);
if (pluginAssembly != null)
{
    foreach (Type currType in pluginAssembly.GetTypes())
    {
        if (typeof(IPlugin).IsAssignableFrom(currType))
        {
            string test = "test";
        }
    }
}
도움이 되었습니까?

해결책

시도 했습니까?

typeof(IPlugin).IsAssignableFrom(currType)

또한 유형 구현하다 인터페이스이지만 그렇지 않습니다 파생 그들로부터. 그만큼 BaseType 속성 및 IsSubclassOf 방법 쇼 파생, 어디에 IsAssignableFrom 파생 또는 구현을 보여줍니다.

편집하다: 당신의 어셈블리에 서명 되었습니까? 그들은로드 할 수 있습니다 조립의 나란히 버전, 이후 Type 객체는 비교됩니다 ReferenceEquals, 두 개의 나란히 어셈블리에서 동일한 유형이 완전히 독립적입니다.

편집 2 : 이 시도:

public Type[] LoadPluginsInAssembly(Assembly otherAssembly)
{
    List<Type> pluginTypes = new List<Type>();
    foreach (Type type in otherAssembly.GetTypes())
    {
        // This is just a diagnostic. IsAssignableFrom is what you'll use once
        // you find the problem.
        Type otherInterfaceType =
            type.GetInterfaces()
            .Where(interfaceType => interfaceType.Name.Equals(typeof(IPlugin).Name, StringComparison.Ordinal)).FirstOrDefault();

        if (otherInterfaceType != null)
        {
            if (otherInterfaceType == typeof(IPlugin))
            {
                pluginTypes.Add(type);
            }
            else
            {
                Console.WriteLine("Duplicate IPlugin types found:");
                Console.WriteLine("  " + typeof(IPlugin).AssemblyQualifiedName);
                Console.WriteLine("  " + otherInterfaceType.AssemblyQualifiedName);
            }
        }
    }

    if (pluginTypes.Count == 0)
        return Type.EmptyTypes;

    return pluginTypes.ToArray();
}

다른 팁

ISASSIGNABLEFROM은 귀하가 찾고있는 것입니다.

Type intType = typeof(IInterface);
foreach (Type t in pluginAssembly.GetTypes())
{
    if (intType.IsAssignableFrom(t))
    {
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top