Autofac - 如何解决模块中注册的类型?

时间:2017-05-23 15:56:05

标签: c# autofac nlog autofac-module

我在ASP.Net MVC应用程序中使用Autofac模块时遇到问题。

我使用NLogModule来"注册" Nlog:

public class NLogModule : Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        registration.Preparing += onComponentPreparing;
    }

    private static void onComponentPreparing(object sender, PreparingEventArgs e)
    {
        var t = e.Component.Activator.LimitType;
        e.Parameters = e.Parameters.Union(
            new[]
            {
                new ResolvedParameter(
                    (p,i) => p.ParameterType == typeof(Portail.Utils.Logging.ILogger),
                    (p, i) => new NLogLogger(LogManager.GetLogger(t.FullName)))
            });
    }

}

我还在构建器中添加了模块:

builder.RegisterModule<NLogModule>();

对于需要我的记录器的构建器中注册的不同服务,一切正常。

现在,我想在文件中记录每个SQL查询。我按照以下文章https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx

最后在我的LoggerCommandInterceptor类中,我需要解析ILogger。但它没有用。

Autofac.Core.Registration.ComponentNotRegisteredException: 'The requested service 'Portail.Utils.Logging.ILogger' has not been registered.

我不明白为什么它不起作用。与服务的唯一区别是我自己创建了LoggerCommandInterceptor的实例

public PortailDbConfiguration()
    {
        SetDatabaseLogFormatter((context, writeAction) => new OneLineFormatter(context, writeAction));
        this.AddInterceptor(new LoggerCommandInterceptor());

    }


public class LoggerCommandInterceptor : IDbCommandInterceptor
{

    #region Fields

    private static ILogger _logger;

    #endregion

    #region Constructors

    public LoggerCommandInterceptor()
    {
        var scope = EngineContext.Current.ContainerManager.Scope();
        _logger = EngineContext.Current.ContainerManager.Resolve<ILogger>();
    }

    #endregion
   ...     

和其他服务一样,Autofac创建实例。

有人可以帮助我吗?

非常感谢。

麦克

0 个答案:

没有答案
相关问题