1

我正在构建一个 WPF 应用程序。我正在使用 Prism 4 和 Unity。我想向应用程序中添加两个 Enterprise Library 5 块,即日志记录和异常处理。我的基础设施类中有一个支持 ILoggerFacade 的单例 LoggerFacadeCustom.cs,我在引导程序中创建了它,它正在生成日志文件。它在其构造函数中“通知”了一个统一容器(第二个代码块)

在哪里为 ExceptionManager 添加 container.resolve?如何在我的引导程序中将异常处理块连接到 ILoggerFacade?如何让所有异常出现在同一个日志中?这是我现有的 bootstrapper.cs

  public class Bootstrapper : UnityBootstrapper {

     protected override ILoggerFacade CreateLogger() {
        return LoggerFacadeCustom.Instance;
     }

     protected override DependencyObject CreateShell() {
        return Container.Resolve<Shell>();
     }

     protected override void InitializeShell() {
        base.InitializeShell();

        App.Current.MainWindow = (Window)Shell;
        App.Current.MainWindow.Show();

     //Other shell stuff...

     }

     protected override IModuleCatalog CreateModuleCatalog() {

        var catalog = new ModuleCatalog();

        //These primary modules must register their own services as if they were acting independantly
        catalog.AddModule(typeof(XmlCommentMergeModule));

        //These support modules require at least one primary module above to be added first
        catalog.AddModule(typeof(ToolboxHeaderModule));
        catalog.AddModule(typeof(ToolboxFooterModule));
        catalog.AddModule(typeof(ToolboxStartModule));
        return catalog;
     }
  }

LoggerFacadeCustom:

  public class LoggerFacadeCustom : ILoggerFacade {

     private static readonly LoggerFacadeCustom _instance = new LoggerFacadeCustom();
     public static LoggerFacadeCustom Instance { get { return _instance; } }

     private LoggerFacadeCustom() {
        var container = new UnityContainer();
        container.AddNewExtension<EnterpriseLibraryCoreExtension>();

        _logWriter = container.Resolve<LogWriter>();
     }

     private readonly LogWriter _logWriter;


     public void Write(string message) { Write(message, null); }

           public void Write(string message, string category, int priority) {
     _logWriter.Write(message, category, priority);
  }

           public void Write(string message, Dictionary<string, object> properties) {
     _logWriter.Write(message, LiteralString.LogCategoryProcess, properties);
  }


     #region ILoggerFacade Members

     public void Log(string message, Category category, Priority priority) {
        throw new NotImplementedException();
     }

     #endregion
  }
4

1 回答 1

0

您的引导程序是应用程序的组合根。您应该在那里注册所有依赖项。而且只有那里。您永远不应该直接在组合根之外引用容器。

如果您的类具有依赖项,则应使用构造函数注入之类的模式注入该依赖项。

不要使用静态类。静态杀死依赖注入和可测试性,并将依赖隐藏到一个点,从任何地方引用所有内容。

使您的记录器外观成为构造函数参数。您可以对错误处理块执行相同的操作。

不要将容器用作 ServiceLocator。这在现代软件架构中被认为是一种反模式

于 2012-11-04T20:31:14.943 回答