我没能找到任何类似的例子,所以我决定问这个问题。
我正在使用 Autofac 注册我的服务层接口(interface),我想知道,我可以将一个注入(inject)到 App.xaml.cs
中吗?
我有自己的日志服务,我想在应用程序出现 fatal error 时运行它。
据我所知,你可以用类似的方式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();
}
}
IoC 在 ViewModelLocator 中初始化:
public class ViewModelLocator
{
IContainer _container;
public ViewModelLocator()
{
_container = BootStrapper.BootStrap();
}
//view models below
}
最佳答案
如果你想给 App
类注入(inject)一个依赖,你应该定义一个自定义的 Main
方法来实例化 App
类:
public class Program
{
[STAThread]
public static void Main(string[] args)
{
ILogService logService = ...;
App app = new App(logService);
app.InitializeComponent();
app.Run();
}
}
如果这样做,请记住将 App.xaml
的 Build Action
从 ApplicationDefinition
更改为 Page
.
关于c# - 如何将依赖项注入(inject) App.xaml.cs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57684916/