如何向App.xaml.cs注入依赖项?

时间:2019-08-28 04:05:40

标签: c# wpf dependency-injection autofac

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

我正在使用Autofac注册我的服务层接口,我想知道是否可以将其中一个注入App.xaml.cs

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

据我所知您可以inject dependency to the window用类似的方式,我可以在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
    }

1 个答案:

答案 0 :(得分:-1)

如果要为App类注入依赖项,则应定义一个自定义的Main方法,在其中实例化App类:

public class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        ILogService logService = ...;
        App app = new App(logService);
        app.InitializeComponent();
        app.Run();
    }
}

如果这样做,请记住将Build Action中的App.xamlApplicationDefinition更改为Page