如何从库中获取网站程序集

时间:2012-08-21 13:42:52

标签: c# asp.net reflection ihttphandler

我的解决方案包括2个项目,一个ASP.NET MVC 3项目 - Company.Web 和一个.NET库项目 - Company.BLL 。该库包含一个实现IHTTP的类 - Company.BLL.Fido

我已将Fido注册为我的web项目的HTTPHandler,并且在ProcessRequest()方法中,我想动态调用Company.Web项目中的方法 - Company.Web.FidoHelper.DoSomething()< / strong>使用反射。

如何获得对 Company.Web 程序集的引用? Assembly.GetCallingAssembly()返回 System.Web ,Assembly.GetEntryAssembly()返回 null ,Assembly.GetAssembly()返回 Company.BLL

通过AppDomain.GetAssemblies(),我看到 Company.Web 包含在结果中,但我的图书馆项目如何知道选择哪一个?我不能硬编码那个选择,因为我计划将这个库与其他项目一起使用。

代码:

namespace Company.BLL
{
    public class Fido: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //hard-coding like this is not acceptable
            var assembly = AppDomain.CurrentDomain.GetAssemblies()
                                     .Where(a => a.FullName
                                     .StartsWith("Company.Web"))
                                     .FirstOrDefault();
            var type = assembly.GetType("Company.Web.FidoHelper");
            object appInstance = Activator.CreateInstance(type);
            type.InvokeMember("DoSomething", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, appInstance, new object[] { context });
            context.Response.End();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

使用此:

Assembly helperAssy = Assembly.GetAssembly(typeof(FidoHelper));

以下是MSDN文档:http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getassembly%28v=vs.100%29.aspx

** 更新 **

好的,所以如果你没有回到Company.BLL的引用,那么你将不得不浏览AppDomain中加载的程序集的所有。这将是混乱的,因为你将不得不查看名称,以找到你想要的东西。

但是这样的事情:

Assembly[] assemblies = AppDomain.Current.GetAssemblies();
Assembly theOne;
foreach(Assembly assy in assemblies)
{
   if(assy.FullName == "Company.Web")
   {
       theOne = assy;
       break;
   }
}
// Do the rest of your work

答案 1 :(得分:0)

以下是我解决问题的方法:

Company.Web 中,创建一个 Fido 类,扩展 Company.BLL.Fido 。不提供任何实现并将 Company.Web.Fido 注册为处理程序而不是 Company.BLL.Fido

Company.BLL.Fido的 ProcessRequest()方法中,HTTP上下文的 CurrentHandler 属性现在引用 Company.Web.Fido ,所以我可以使用该类型获得对 Company.Web 程序集的引用。

var assembly = Assembly.GetAssembly(context.CurrentHandler.GetType()); 
//assembly = Company.Web

现在,我可以使用反射来调用Company.Web.FidoHelper.DoSomething(context)。

代码:

namespace Company.BLL
{
    public class Fido: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //hard-coding like this is not acceptable
            var assembly = Assembly.GetAssembly(context.CurrentHandler.GetType());
            var type = assembly.GetType("Company.Web.FidoHelper");
            object appInstance = Activator.CreateInstance(type);
            type.InvokeMember("DoSomething", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, appInstance, new object[] { context });
            context.Response.End();
        }
    }
}