查找类以按名称实例化而无需命名空间或程序集? (.网) [英] Find class to instantiate by name without namespace or assembly? (.NET)

查看:72
本文介绍了查找类以按名称实例化而无需命名空间或程序集? (.网)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过名称(字符串)实例化一个类而不指定名称空间或程序集.像这样(Unity语法):

I'd like to instantiate a class by name (a string) without specifying a namespace or assembly. Like this (Unity syntax):

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

将实例化它找到的第一个IProcessor,称为​​SpecialProcessor.也许

would instantiate the first IProcessor it finds called SpecialProcessor. Maybe

MyNamespace.SpecialProcessor

我想避免每次有人添加新处理器时都必须在配置中创建条目.我可以为所有候选程序集添加一个条目.

I'd like to avoid having to create an entry in a config every time somebody adds a new processor. I'm fine with having an entry for all candidate assemblies though.

我可以将IoC容器用于此类用途还是应该自己包装?

Can I use an IoC container for something like this or should I roll my own?

推荐答案

此处提供的功能与您想要的功能非常相似.您可以对其进行修改,以非常轻松地根据特定的类名进行过滤.

Here's a function that does something very similar to what you want. You can modify it to filter based on a specific class name pretty easily.

这些功能引用了一些我们用于日志记录和异常处理的实用程序.在这种情况下,您需要用通常的操作替换它们.

These functions have references to a few utilities we use for logging and exception handling. You'll need to replace them with whatever you normally do in these situations.

    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();
    }

这篇关于查找类以按名称实例化而无需命名空间或程序集? (.网)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆