曹永思

导航

asp.net动态加载程序集创建指定类的实例及调用指定方法

 

以下类中有三个方法:

LoadAssembly:加载指定路径的程序集
GetInstance:根据Type动态获取实例,用泛型接到返回的类型
ExecuteMothod:执行实例中的指定方法
    /// <summary>
    /// 继承自MarshalByRefObject表示允许跨域通信
    /// </summary>
    public class RemoteLoader : MarshalByRefObject
    {
        private Assembly _assembly;

        public void LoadAssembly(string assemblyFile)
        {
            try
            {
                _assembly = Assembly.LoadFrom(assemblyFile);
                //return _assembly;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public T GetInstance<T>(string typeName) where T : class
        {
            if (_assembly == null) return null;
            var type = _assembly.GetType(typeName);
            if (type == null) return null;
            return Activator.CreateInstance(type) as T;
        }

        public void ExecuteMothod(string typeName, string methodName)
        {
            if (_assembly == null) return;
            var type = _assembly.GetType(typeName);
            var obj = Activator.CreateInstance(type);
            Expression<Action> lambda = Expression.Lambda<Action>(Expression.Call(Expression.Constant(obj), type.GetMethod(methodName)), null);
            lambda.Compile()();
        }
    }

 

posted on 2017-06-23 17:08  曹永思  阅读(214)  评论(0编辑  收藏  举报