从另一个程序集引导Windows窗体项目

本文关键字:Windows 窗体 项目 另一个 程序集 | 更新日期: 2023-09-27 18:15:13

我在将洋葱架构与Windows窗体UI层结合时遇到了一个障碍。问题是我的IoC配置方法从未被击中。IoC设置在依赖项解析程序集中进行:

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

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

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

在项目

。DependencyResolution:

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

OutputTo OutputTargets.txt:

..'Project.UI'bin    
在项目

。UI:

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

OutputTo正确复制DependencyResolution's DLL文件到Ui's bin,但IocConfig.RegisterDependencies从未运行。

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

从另一个程序集引导Windows窗体项目

刚刚用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属性)。