查找类以在没有命名空间或程序集的情况下按名称实例化? (。净)

时间:2010-01-29 04:29:37

标签: c# ioc-container

我想在不指定命名空间或程序集的情况下按名称(字符串)实例化一个类。像这样(Unity语法):

var processor = container.Resolve<IProcessor>("SpecialProcessor");

将实例化它发现的第一个叫做SpecialProcessor的IProcessor。也许

MyNamespace.SpecialProcessor

每当有人添加新处理器时,我都希望避免在配置中创建条目。我可以为所有候选人集会提供参赛作品。

我可以将IoC容器用于这样的事情,还是应该自己动手?

2 个答案:

答案 0 :(得分:1)

这是一个与你想要的东西非常相似的功能。您可以很容易地修改它以根据特定的类名进行过滤。

这些函数引用了我们用于记录和异常处理的一些实用程序。你需要用在这些情况下通常做的任何东西来替换它们。

    public static T FindAndCreate<T>(bool localOnly, bool exportedOnly)
    {
        Type[] types = FindAssignableClasses(typeof(T), localOnly, exportedOnly, false);
        if (types.Length == 0)
        {
            return default(T);
        }
        if (types.Length != 1)
        {
            Log.Warn(typeof(ReflectionUtil),
                     "FindAndCreate found {0} instances of {1} whereas only 1 was expected.  Using {2}.  {3}",
                     types.Length,
                     typeof(T).FullName,
                     types[0].FullName,
                     String.Join("\r\n  ", Array.ConvertAll<Type, String>(types, GetFullName)));
        }
        try
        {
            return (T)Activator.CreateInstance(types[0]);
        }
        catch (Exception ex)
        {
            throw ExceptionUtil.Rethrow(ex,
                                        "Unable to create instance of {0} found for interface {1}.",
                                        types[0].FullName,
                                        typeof(T).FullName);
        }
    }

    public static Type[] FindAssignableClasses(Type assignable, bool localOnly, bool exportedOnly, bool loadDll)
    {
        var list = new List<Type>();
        string localDirectoryName = Path.GetDirectoryName(typeof(ReflectionUtil).Assembly.CodeBase);

        if (loadDll && !_loadedAllDlls)
        {
            foreach (string dllPath in Directory.GetFiles(localDirectoryName.Substring(6), "*.dll"))
            {
                try
                {
                    Assembly.LoadFrom(dllPath);
                }
                catch
                {
                    // ignore
                }
            }
            _loadedAllDlls = true;
        }

        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
        {
            try
            {
                if (localOnly && Path.GetDirectoryName(asm.CodeBase) != localDirectoryName)
                {
                    continue;
                }

                Type[] typesInAssembly;
                try
                {
                    typesInAssembly = exportedOnly ? asm.GetExportedTypes() : asm.GetTypes();
                }
                catch
                {
                    continue;
                }

                foreach (Type t in typesInAssembly)
                {
                    try
                    {
                        if (assignable.IsAssignableFrom(t) && assignable != t)
                        {
                            list.Add(t);
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Debug(
                            typeof(ReflectionUtil),
                            String.Format(
                                "Error searching for types assignable to type {0} searching assembly {1} testing {2}{3}",
                                assignable.FullName,
                                asm.FullName,
                                t.FullName,
                                FlattenReflectionTypeLoadException(ex)),
                            ex);
                    }
                }
            }
            catch (Exception ex)
            {
                // ignore dynamic module error, no way to check for this condition first
                // http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/7b02223aefc6afba/c8f5bd05cc8b24b0
                if (!(ex is NotSupportedException && ex.Message.Contains("not supported in a dynamic")))
                {
                    Log.Debug(
                        typeof(ReflectionUtil),
                        String.Format(
                            "Error searching for types assignable to type {0} searching assembly {1} from {2}{3}",
                            assignable.FullName,
                            asm.FullName,
                            asm.CodeBase,
                            FlattenReflectionTypeLoadException(ex)),
                        ex);
                }
            }
        }

        return list.ToArray();
    }

答案 1 :(得分:0)

听起来您有一个插件架构,并且您希望允许其他组件提供IProcessor的实现,而无需更新某些主配置文件。如果是这种情况,那么我认为您最适​​合使用MEF(托管扩展性框架)(Website)。

这是一个旨在允许此类行为的框架。一旦建立了要从中加载组件的程序集目录,导入IProcessor实例的集合就像以下一样简单

var processors = container.GetExportedValues<IProcessor>();

有许多在线MEF教程可以帮助您入门。