Autofac - How to resolve a type registered in a module?

774 views Asked by At

I have a problem using Autofac Module in my ASP.Net MVC Application.

I use a NLogModule to "register" 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)))
            });
    }

}

I also add the module in my builder :

builder.RegisterModule<NLogModule>();

Everything works fine for the differents services registered in the builder which need my logger.

So now, I want to log every SQL Queries in a file. I follow the following article https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx

Finally in my LoggerCommandInterceptor class, I need to resolve the ILogger. But it doesn't work.

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

I don't understand why it doesn't work. The only difference with the services is that I create the instance of my LoggerCommandInterceptor myself

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
   ...     

and with the other services, Autofac create instances.

Can someone help me?

Thanks a lot.

Mike.

0

There are 0 answers