我没有找到任何类似的例子,所以决定提出这个问题。
我正在使用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
}
BootStrapper
执行之前,System.Windows.Application
已经被创建。我通过在我的App.xaml的<Application.Resources>
中定义一个BootStrapper
来实现这一点。 - user585968