我没有找到类似的例子,所以我决定问这个问题。
我正在使用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
}
答案 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.xaml
从ApplicationDefinition
更改为Page
。