在不重新启动应用程序的情况下添加对asp.net mvc应用程序的dll引用

时间:2014-12-23 15:01:52

标签: c# asp.net .net asp.net-mvc dll

我正在尝试为我的应用添加新的dll。我尝试过使用Ninject:

var standardKernel = new StandardKernel();
ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(standardKernel));
standardKernel.Load<MyPluginBootstrapper>();
standardKernel.Bind<IHelloWorldService>().To<HelloWorldService>();
DependencyResolver.SetResolver(new MyDependencyResolver(standardKernel));

我尝试过使用:

var _fullPluginPath = Path.Combine(path, "App2.Plugin.dll");
AppDomain.CurrentDomain.Load(Assembly.LoadFrom(_fullPluginPath).GetName());

当我尝试访问新dll中的控制器时,我总是遇到同样的错误:

Compilation Error
Compiler Error Message: CS0246: The type or namespace name 'App2' could not be found (are     you missing a using directive or an assembly reference?)
Line 26:     using System.Web.Optimization;
Line 27:     using System.Web.Routing;
Line 28:     using App2.Plugin;
Line 29:     
Line 30:     

Source File: c:\Users\wilhem\AppData\Local\Temp\Temporary ASP.NET Files\root\0c41d57d\e08d7bc3\App_Web_index.cshtml.244a139d.hzhandta.0.cs    Line: 28 

我正在实现像基于插件的架构,我希望能够在不重新启动应用程序的情况下添加新的dll。有任何想法与上面的代码?

1 个答案:

答案 0 :(得分:3)

您可以随时随地加载程序集。但是不要将它放在应用程序/bin目录中。 把它放在另一个位置,比如/plugins。不要让它公开可见。

创建一个之前已知的公共接口,使用IMyInterface.DoStuff()等函数并返回一个字符串,无论如何。

然后你可以使用反射来调用它:

Assembly assembly = Assembly.LoadFrom(Server.MapPath("~/plugins/myDll.dll"));
Type type = assembly.GetType("MyClass");
object instanceOfMyType = Activator.CreateInstance(type);

确保您的MyClass实现您的commom IMyInterface。 你将无法看到你的课程:

MyClass obj = new MyClass();

这将重置您的ASP.NET应用程序。 但通过反思,你将能够做到这样的事情:

string myReturn = ((IMyInterface)instanceOfMyType).DoStuff();