使用带有动态加载的DLL的Castle Windsor解析控制器

时间:2016-02-08 15:06:34

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

加载Web应用程序后,Castle Windsor无法找到控制器。路径''的控制器未找到或未实现IController。当我查看内核(在CustomControllerFactory中)时,我看到所有控制器都已正确注册。

主MVC应用程序加载3个其他DLL。当我们直接在Visual Studio中引用DLL并加载插件类型时,它正在工作。但是当动态加载它时,它表示失败。当我请求URL时,传递给GetControllerInstance的上下文是正确的,但Type参数为null。

我使用Assembload.LoadFrom加载程序集。然后我检索Types foreach模块,它是Plugin的子类。这导致我有3种类型。

Assembly assembly = Assembly.LoadFrom(module);

Type pluginType = assembly.GetTypes()
                    .Single(x => x.IsSubclassOf(typeof(Plugin)));

然后我创建了一个插件实例,用于注册路由。

(IPlugin)Activator.CreateInstance(type))

的RegisterRoutes:

    public static void RegisterRoutes(RouteCollection routes, IEnumerable<IPlugin> plugins)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        var pluginRouteDefaults = new {action = "Index", id = UrlParameter.Optional};
        foreach (var plugin in plugins)
        {
            var context = new AreaRegistrationContext(plugin.Area, routes);
            context.MapRoute(plugin.Area, $"{plugin.Area}/{{controller}}/{{action}}/{{id}}", pluginRouteDefaults, plugin.GetControllerNamespaces().ToArray());
        }

        routes.MapRoute(
              name: "Default",
              url: "{area}/{controller}/{action}/{id}",
              defaults: new { area = "Framework", controller = "Home", action = "Index", id = UrlParameter.Optional },
              namespaces: new string[] { "Web.Framework.Controllers" }
              );
    }

CustomControllerFactory:

public class CustomControllerFactory : DefaultControllerFactory
{
    private readonly IKernel _kernel;

    public VlcControllerFactory(IKernel kernel)
    {
        this._kernel = kernel;
    }

    public override void ReleaseController(IController controller)
    {
        _kernel.ReleaseComponent(controller);
    }

    protected override IController GetControllerInstance(RequestContext context, Type controllerType)
    {
        if (controllerType == null)
        {
            return base.GetControllerInstance(context, controllerType);
        }
        try
        {
            return (IController)_kernel.Resolve(controllerType);
        }
        catch
        {
            return base.GetControllerInstance(context, controllerType);
        }
    }
}

注册控制器。执行此操作后,我可以看到在Visual Studio的“模块”窗口中加载了DLL。此外,AppDomain.CurrentDomain.GetAssemblies()表示已加载DLL。

container.Register(
            Classes.FromThisAssembly().BasedOn<IController>().LifestyleTransient());

我找到Dll的MvcApplication类。

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var directories = Directory.GetDirectories("C:\Projects\main\modules").Where(x => !x.EndsWith("Framework"));
        string subPath = GetSubPath();

        List<Type> pluginTypes = GetPluginTypes(directories, subPath);
        var plugins = GetIPlugins(pluginTypes);
        Launcher.CreateWindsorContainer(plugins.ToArray());
    }

    private static List<IPlugin> GetIPlugins(List<Type> pluginTypes)
    {
        List<IPlugin> plugins = new List<IPlugin>{new MvcInstaller()};

        pluginTypes.ForEach(type => plugins.Add((IPlugin) Activator.CreateInstance(type)));
        return plugins;
    }

    private static List<Type> GetPluginTypes(IEnumerable<string> directories, string subPath)
    {
        List<Type> pluginTypes = new List<Type>();

        foreach (string directory in directories)
        {
            string module = Directory.GetFiles(directory + subPath).SingleOrDefault(x => x.EndsWith("Plugin.dll"));

            if (!string.IsNullOrEmpty(module))
            {
                Assembly assembly = Assembly.LoadFrom(module);
                Type pluginType = assembly.GetTypes()
                    .Single(x => x.IsSubclassOf(typeof(Plugin)));
                pluginTypes.Add(pluginType);
            }
        }
        return pluginTypes;
    }

    private static string GetSubPath()
    {
        #if DEBUG
        var subPath = @"\bin\Debug\";
        #else
        subPath = @"\bin\Release\";
        #endif

        return subPath;
    }
}

当我省略此代码并直接引用其他Dll并执行以下操作时:

Launcher.CreateWindsorContainer(new PluginA(), new PluginB(), new MVCPlugin());

然后它完美无缺,但是在加载Dll时,控制器的解析失败了。为什么Castle Windsor在请求控制器时找不到类型?

1 个答案:

答案 0 :(得分:3)

这里的问题不是控制器的Windsor分辨率。 DefaultControllerType.GetControllerType()方法可能会返回null,因为您没有将程序集添加到BuildManager(使用BuildManager.AddReferencedAssembly(assembly))。请注意,您只能在应用程序启动前调用此方法,因此您需要使用[assembly:PreApplicationStartupMethod(typeof(...SomeType), "PublicStaticVoidMethodOnSomeType")