【问题标题】:Want to implement Dependency Injection in a WPF application想要在 WPF 应用程序中实现依赖注入
【发布时间】:2019-11-20 04:34:09
【问题描述】:

在现有的 WPF 应用程序中,我想实现依赖注入。 所以在我的应用程序启动时,我设置了 di 容器并让窗口像这样构建:

var builder = new ContainerBuilder();

builder.RegisterType<SplashScreen>().AsSelf();
builder.RegisterType<ILogger>().As(Logger);

Container = builder.Build();

using (var scope = Container.BeginLifetimeScope())
{
      var window = scope.Resolve<SplashScreen>();
      window.Show();
      window.Initialiseren();
}

在我的窗口中,我有一个按钮可以调用具有多个依赖项的另一个窗口?

public partial class AnotherWindow
{
      public AnotherWindow(ILogger)
      {
            ...
      }
}

public partial class Window
{
      public void Button_Click()
      {
            AnotherWindow w = new AnotherWindow(new Logger());
            w.Show();

      }
}

我如何使用我的容器来解析另一个窗口,而无需将我的容器到处传递? 我的目标是使用 autofac 初始化 ILogger。

提前谢谢你!

【问题讨论】:

    标签: c# wpf dependencies code-injection


    【解决方案1】:

    例如,您可以使用App 类的静态属性公开从Build() 返回的IContainer:

    internal static IContainer Container { get; set; }
    

    然后您可以从任何视图访问它:

    public void Button_Click()
    {
        AnotherWindow w;
        using (var scope = App.Container.BeginLifetimeScope())
            w = scope.Resolve<SplashScreen>();
        w?.Show();
    }
    

    【讨论】:

    • 是的,这是一个非常有用的答案,目前我是这样实现的。但我担心我在互联网上到处都有人说只有程序的启动才能访问容器?使用静态容器是依赖注入的反模式。您对此有何看法?
    • 我同意,但这取决于您如何设置和构建应用程序。您通常会实现 MVVM 设计模式,并为视图模型注入他们需要的任何依赖项,而不是显式使用容器。但是您最初的问题是关于如何避免传递容器。
    • 但是你怎么能在 wpf 应用程序中不直接或间接访问你的容器来显示一个带有依赖注入的窗口呢?如果不调用容器,我真的看不到这样做的方法。
    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 2010-09-22
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多