如何将依赖注入到 App.xaml.cs 中?

3

我没有找到任何类似的例子,所以决定提出这个问题。

我正在使用Autofac来注册我的服务层接口,我想知道,我能否将其注入到App.xaml.cs中?

我有自己的日志服务,在应用程序发生致命错误时希望运行它。

据我所知,你可以通过向窗口注入依赖项以相似的方式完成,我能不能在App.xaml.cs中做同样的事情呢?

最初的回答:

public partial class App : Application
    {
        private readonly ILogService _log;

        public App()
        {

        }

        public App(ILogService log) : this()
        {
            _log = log;
        }

        async Task App_DispatcherUnhandledExceptionAsync(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            _log.Error("App.xaml.cs exception: " + e.Exception.Message);

            await _log.SaveAllLinesAsync();

            e.Handled = true;
        }
    }

Autofac IoC:

public class BootStrapper
    {
        /// <summary>
        /// IoC container
        /// </summary>
        /// <returns></returns>
        public static IContainer BootStrap()
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<EventAggregator>()
              .As<IEventAggregator>().SingleInstance();

            builder.RegisterType<LogService>()
              .As<ILogService>().SingleInstance();

            builder.RegisterType<DeleteView>().AsSelf();
            builder.RegisterType<DeleteViewModel>().AsSelf().SingleInstance();
            builder.RegisterType<PhraseView>().AsSelf();
            builder.RegisterType<PhraseViewModel>().AsSelf().SingleInstance().WithParameter(new NamedParameter("searchPhrase", ""));
            builder.RegisterType<PopulateDictionaries>().AsSelf().SingleInstance();

            return builder.Build();
        }
    }

在ViewModelLocator中进行IoC初始化:

最初的回答
public class ViewModelLocator
    {
        IContainer _container;
        public ViewModelLocator()
        {
            _container = BootStrapper.BootStrap();
        }

        //view models below
    }

对于那些首先加载/执行的位置,我通常会直接调用我的依赖容器来解决任何依赖关系。你试过这样做了吗?而不是通过构造函数注入? - undefined
@MickyD 但是我有一个带有依赖注入的第二个构造函数。 - undefined
如果它与Caliburn和Windsor类似,那么在BootStrapper执行之前,System.Windows.Application已经被创建。我通过在我的App.xaml<Application.Resources>中定义一个BootStrapper来实现这一点。 - user585968
是的,我担心这一点,App.xaml.cs中带有依赖注入构造函数的部分将不会被使用,并且会使用默认构造函数创建。 - undefined
你如何设置容器?你的应用程序入口点是什么?请向我们展示您调用“BootStrap”方法的位置。 - undefined
显示剩余6条评论
1个回答

0
如果你想给App类注入一个依赖项,你应该定义一个自定义的Main方法,在这个方法中实例化App类。
public class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        ILogService logService = ...;
        App app = new App(logService);
        app.InitializeComponent();
        app.Run();
    }
}

如果你这样做,请记得将 App.xamlBuild ActionApplicationDefinition 改为 Page

@bakunet:你试过这个方法了吗?这是注入App类的方式,与那些给负评的人认为的恰好相反 :) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接