【问题标题】:Onion Architecture Logging NHibernate洋葱架构日志记录 NHibernate
【发布时间】:2012-06-18 20:54:17
【问题描述】:

我正在使用基于 this 实现的洋葱架构的架构。我决定挑战自己,用 NLog 更改 NHibernates 默认记录器(log4net)。我了解如何配置 NLog,但在我的 LogerFactory 类中解决我的记录器的依赖项时遇到了麻烦。目前,我的 NHibernate 项目只知道我的日志接口。如何让我的 NHibernate 项目解决依赖关系?

这是我现在的程序结构: 控制台应用程序初始化 ninject 并设置我的模块,包括我的 LoggingModule 和我的 RepositoryModule。当我第一次需要我的存储库中的某些东西时,我的 SessionHelper 类会构建我的会话并配置 NHibernate。这是 NHibernate 调用我的 LoggerFactory 的地方(LoggerFactory 实现 NHibernates ILoggerFactory)。 NHibernate 调用 LoggerFor(Type type);类型作为 NHibernate.Cfg.Configuration 传入。从这里开始,我需要通过 ILoggingService 获取 NLog 的实例,这就是我感到困惑的地方。我如何在这里解决这种依赖关系?我的控制台应用程序知道分辨率,因为那是我构建内核并加载模块的地方。我只是在这里设置另一个内核吗?解决这个问题的最佳方法是什么?

编辑:这是我当前的代码:

程序.cs

namespace ZeroBase.ManualConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = CreateKernel();

            CoreService service = new CoreService(
                kernel.Get<ZeroBase.Domain.Interfaces.IUserRepository>(), 
                kernel.Get<ZeroBase.Domain.Interfaces.ICommentRepository>());

            //.........

        }

        static IKernel CreateKernel()
        {
            IKernel kernel = new StandardKernel();
            RegisterServices(kernel);
            return kernel;
        }

        static void RegisterServices(IKernel kernel)
        {
            // Bind Core Service
            kernel.Bind<ICoreService>().To<CoreService>();

            // Add data and infrastructure modules
            var modules = new List<INinjectModule>
            {
                new ConfigModule(),
                new LoggingModule(),
                new RepositoryModule()
            };

            kernel.Load(modules);
        }

    }
}

LoggingModule.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject.Modules;
using ZeroBase.Infrastructure.Interfaces;
using NLog.Config;
using NLog;
using ZeroBase.Infrastructure.Logging;

namespace ZeroBase.Infrastructure.DependencyResolution
{
    public class LoggingModule : NinjectModule
    {
        public override void Load()
        {
            ILoggingService logger = GetLoggingService();
            Bind<ILoggingService>().ToConstant(logger);
        }

        private ILoggingService GetLoggingService()
        {
            ConfigurationItemFactory.Default.LayoutRenderers
                .RegisterDefinition("utc_date", typeof(UtcDateRenderer));
            ConfigurationItemFactory.Default.LayoutRenderers
                .RegisterDefinition("web_variables", typeof(WebVariablesRenderer));
            ILoggingService logger = (ILoggingService)LogManager.GetLogger("NLogLogger", typeof(LoggingService));
            return logger;
        }
    }
}

RepositoryModule.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Ninject;
using Ninject.Modules;

using ZeroBase.Infrastructure.Interfaces;
using ZeroBase.Domain.Interfaces;
using ZeroBase.Infrastructure.Data;

namespace ZeroBase.Infrastructure.DependencyResolution
{
    public class RepositoryModule : NinjectModule
    {
        public override void Load()
        {
            SetupLogging();
            BindRepositories();
        }

        private void SetupLogging()
        {
            // Get logging service
            var loggingService = Kernel.Get<ILoggingService>();

        }

        private void BindRepositories()
        {
            // Get config service
            var configService = Kernel.Get<IConfigService>();

            // Bind repositories
            Bind<IUserRepository>().To<UserRepository>()
                .WithConstructorArgument("connectionString",    configService.ZeroBaseConnection);
            Bind<ICommentRepository>().To<CommentRepository>()
                .WithConstructorArgument("connectionString",    configService.ZeroBaseConnection);
        }
    }
}

RepositoryBase.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZeroBase.Domain.Interfaces;

namespace ZeroBase.Infrastructure.Data
{
    public class RepositoryBase<T> : IRepositoryBase<T>
    {
        protected SessionHelper _nhibernate;
        protected string _connectionString;

        public RepositoryBase(string connectionString)
        {
            _connectionString = connectionString;
            _nhibernate = new SessionHelper(_connectionString);
        }

        //....
    }
}

SessionHelper.cs 构建 NHibernate 会话并进行配置。请注意,正在注入 connectionString。我可以在这里轻松地注入日志服务。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using ZeroBase.Infrastructure.Data;
using FluentNHibernate.Automapping;
using ZeroBase.Domain.Entities;
using ZeroBase.Infrastructure.Interfaces;

namespace ZeroBase.Infrastructure.Data
{
    public class SessionHelper
    {
        private ISessionFactory _sessionFactory;
        private string _connectionString;

        public SessionHelper(string connectionString)
        {
            _connectionString = connectionString;
        }

        private ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();

                return _sessionFactory;
            }
        }

        private void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()

                // Set up database connection
                .Database(MsSqlConfiguration.MsSql2005
                    .ConnectionString(x => x.Is(_connectionString))
                    //.ShowSql()
                )

                // Use class mappings
                .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf<UserMap>()
                    .AddFromAssemblyOf<ZeroBase.Infrastructure.Data.RACS3.UserMap>())

                .ExposeConfiguration(c => {
                        c.SetInterceptor(new AuditInterceptor());
                    }
                )

                .BuildSessionFactory();
        }

        public ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}

LoggerFactory.cs 通过 app.config 为 NHibernate 配置以用于其日志记录。这是我遇到依赖问题的地方。这与 NHibernate 并存。我可以在这里轻松地引用 NLog 并将其与 NHibernate 连接起来,但我不希望 NHibernate 关心我使用的是什么日志记录框架。这就是为什么我只想处理我的接口并让 Ninject 注入我的具体实现。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using ZeroBase.Infrastructure.Interfaces;

namespace ZeroBase.Infrastructure.Data
{
    public class LoggerFactory : ILoggerFactory
    {
        public IInternalLogger LoggerFor(Type type)
        {
            //ILoggingService logService;

            // Get resolved LoggingService

            //return new NLogLogger(LogManager.GetLogger(type.FullName));
            //return new Logger(logService.GetLogger(type.FullName));
            return null;
        }

        public IInternalLogger LoggerFor(string keyName)
        {
            //ILoggingService logService;

            // Get resolved LoggingService

            //return new NLogLogger(LogManager.GetLogger(keyName));
            //return new Logger(logService.GetLogger(keyName));
            return null;
        }
    }

    public class Logger : IInternalLogger
    {
        private readonly ILoggingService logger;

        public Logger(ILoggingService _logger)
        {
            logger = _logger;
        }

        //....
    }
}

【问题讨论】:

  • 一个示例代码可能会有所帮助。很难理解真正的问题是什么......

标签: c# nhibernate ninject nlog onion-architecture


【解决方案1】:

为什么不能在初始化内核后立即将静态内核属性添加到 LoggerFactory 类并在 Program.Main 中设置?

然后在您的 LoggerFor 实现中,您只需引用静态内核属性即可获得正确绑定的实现。

【讨论】:

  • 基于此,我能够让它工作。在我的会话助手中,我现在注入 LoggingService,所以在配置 NHibernate 之前,我在 LoggerFactory 中设置静态属性。
【解决方案2】:

【讨论】:

  • 这里只展示了如何集成NLog,而不是如何解决依赖问题。
猜你喜欢
  • 2015-02-23
  • 2011-10-09
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2014-06-22
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多