代码之家  ›  专栏  ›  技术社区  ›  Neil Smith

从另一个程序集启动Windows窗体项目

  •  2
  • Neil Smith  · 技术社区  · 10 年前

    我在将洋葱架构与 Windows Forms UI层。问题是我的 IoC config方法从未命中。IoC设置在依赖解析程序集中进行:

    Project.Core
    Project.Infrastructure
    Project.UI                   <- Startup project 
    Project.DependencyResolution <- IoC configuration
    

    我希望我的UI层除了依赖于 Project.Core .

    在我使用这种架构的web项目中,我使用WebActivatorEx和OutputTo来引导IoC。因为我很熟悉,所以我决定在这里使用相同的方法,但它的表现不如预期。我不确定是我的问题还是Windows窗体的问题,所以我的设置如下:

    在Project.DependencyResolution中:

    [assembly: WebActivatorEx.PreApplicationStartMethod(
        typeof (IocConfig), "RegisterDependencies")]
    
    public class IocConfig
    {
        public static void RegisterDependencies() {
            // this is never executed
        }
    }
    

    OutputTo的OutputTargets.txt:

    ..\Project.UI\bin    
    

    在Project.UI中:

    static class Program
    {
        static void Main() {
            WebActivatorEx.ActivationManager.RunPreStartMethods();
            Application.Run(...);
        }
    }
    

    输出到副本 DependencyResolution's DLL文件转移到 Ui's bin正确,但 IocConfig.RegisterDependencies 永远不会跑。

    那么,我如何从自己的程序集设置IoC,其中Windows窗体项目是启动项目?

    1 回复  |  直到 10 年前
        1
  •  1
  •   Marcel N.    10 年前

    刚刚用WebActivatorEx 2.0.0.5(NuGet中的最新版本)测试了这一点。工作正常。通过在中向控制台打印内容进行检查 RegisterDependencies .

    无论如何,它与作为WinForms应用程序没有任何关系(可以是控制台应用程序,它仍然可以工作)。

    我现在唯一想到的是,您的UI程序集不在其他程序集(包括WebActivatorEx)的旁边。我检查了它的源代码,它依赖于它的存在,因为它在那里查找所有DLL。你能确定集会在他们应该去的地方吗?

    此外,WebActivatorEx在其源代码中包含以下内容:

                try
                {
                    return assembly.GetCustomAttributes(
                        typeof(T),
                        inherit: false).OfType<T>();
                }
                catch
                {
                    // In some very odd (and not well understood) cases, GetCustomAttributes throws. Just ignore it.
                    // See https://github.com/davidebbo/WebActivator/issues/12 for details
                    return Enumerable.Empty<T>();
                }
    

    因此,如果您没有及时找到原因,我建议您获取WebActivatorEx源代码并使用它来调试行为。您还可以看到它加载的程序集 ActivationManager.RunPreStartMethods (实际上是私人静态 Assemblies 属性)。