棱镜2.1:从App.xaml访问IOC容器?

时间:2009-12-16 22:31:49

标签: log4net prism

我正在创建一个Prism 2.1应用程序,我在其中实现了日志记录,使用Log4Net从ILoggerFacade派生的自定义记录器中。记录效果很好;我只是针对IOC容器解决ILoggerFacade,它返回我的记录器,我以通常的方式发送消息。

这是我的问题:我想记录应用程序出口,这样做的逻辑方法似乎是覆盖App.xaml.cs中的OnExit()。但我无法弄清楚如何从App.xaml.cs获取对Container的引用,以便我可以解析我的记录器。

我可以从App.xaml.cs引用Prism IOC容器吗?如果是这样,怎么样?感谢。

2 个答案:

答案 0 :(得分:2)

如果您在App.xaml.cs中使Bootstrapper全局化,那么您可以访问其中的Container。

public partial class App : Application
{
    private static UnityBootstrapper bootstrapper;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        bootstrapper = new MyBootstrapper();
        bootstrapper.Run();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        ILoggerFacade logger = bootstrapper.Container.Resolve<ILoggerFacade>();
        logger.Log("Application Exitting", Category.Info, Priority.Low);

        base.OnExit(e);
    }
}

答案 1 :(得分:0)

在我的Prism 4 MEF应用程序中,我无法通过bootstrapper实例访问Container(Container属性受到保护)。

对于这样的功能,我在我的bootstrapper类中创建了一些特殊的方法,用于获取或设置所需的对象,如logger或其他东西。

对于Cameron变体,它看起来像这样:

public partial class App : Application
{
    private Bootstrapper _bootstrapper;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        _bootstrapper = new MyBootstrapper();
        _bootstrapper.Run();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        ILoggerFacade logger = bootstrapper.GetLogger();
        logger.Log("Application Exitting", Category.Info, Priority.Low);

        base.OnExit(e);
    }
}

class MyBootstrapper : MefBootstrapper
{
    public ILoggerFacade GetLogger()
    {
        return Container.GetExportedValue<ILoggerFacade>();
        // as for Logger you can get it by property of Bootstrapper class:
        // return Logger;
    }

    ...
}