Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9207179
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T00:19:57+00:00 2026-06-18T00:19:57+00:00

I am trying to add NLog my Web Api project with Autofac. But i

  • 0

I am trying to add NLog my Web Api project with Autofac. But i have problems.

After installed NLog package from NuGet, i added following files to my project.
(Because of following different posts and examples it might be confused)

ILogger.cs

 public interface ILogger {
        void Debug(string message);
        void Trace(string message);
        void Info(string message);
        void Warning(string message);
        void Error(string message);
        void Error(string message, Exception exception);
        void Fatal(string message);
        void Fatal(string message, Exception exception);
    }

LoggerAttribute.cs

[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class)]
    public class LoggerAttribute : Attribute {
        public readonly string Name;

        public LoggerAttribute(string name) {
            Name = name;
        }
    }

NLogger.cs

public class NLogger : ILogger {
        private readonly NLog.Logger logger;

        public NLogger(Type loggerType) {
             logger = LogManager.GetLogger(loggerType.FullName);
        }

        public void Debug(string message) {
            logger.Debug(message);
        }

        public void Trace(string message) {
            logger.Trace(message);
        }

        public void Info(string message) {
            logger.Info(message);
        }

        public void Warning(string message) {
            logger.Warn(message);
        }

        public void Error(string message) {
            logger.Error(message);
        }

        public void Error(string message, Exception exception) {
            logger.ErrorException(message, exception);
        }

        public void Fatal(string message) {
            logger.Fatal(message);
        }

        public void Fatal(string message, Exception exception) {
            logger.FatalException(message, exception);
        }
    }

NLogModule.cs

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


        static void OnComponentPreparing(object sender, PreparingEventArgs e) {
            var typePreparing = e.Component.Activator.LimitType;

            // By default, the name supplied to the logging instance is the name of the type in which it is being injected into.
            string loggerName = typePreparing.FullName;

            //If there is a class-level logger attribute, then promote its supplied name value instead as the logger name to use.
            var loggerAttribute = (LoggerAttribute)typePreparing.GetCustomAttributes(typeof(LoggerAttribute), true).FirstOrDefault();
            if(loggerAttribute != null) {
                loggerName = loggerAttribute.Name;
            }

            e.Parameters = e.Parameters.Union(new Parameter[]
        {
            new ResolvedParameter(
                (p, i) => p.ParameterType == typeof (ILogger),
                (p, i) =>
                {
                    // If the parameter being injected has its own logger attribute, then promote its name value instead as the logger name to use.
                    loggerAttribute = (LoggerAttribute)
                    p.GetCustomAttributes(typeof(LoggerAttribute),true).FirstOrDefault();
                    if (loggerAttribute != null)
                    {
                        loggerName = loggerAttribute.Name;
                    }

                    // Return a new Logger instance for injection, parameterised with the most appropriate name which we have determined above.
                    return LogManager.GetLogger(loggerName);
                }),

            // Always make an unamed instance of Logger available for use in delegate-based registration e.g.: Register((c,p) => new Foo(p.TypedAs<Logger>())
            new TypedParameter(typeof(ILogger), LogManager.GetLogger(loggerName))
        });
        }
    }

TestController.cs

 public class TestController : ApiController
    {
        private IUnitOfWork uow;
        private ILogger _logger;
        // GET api/test
        public TestController(IUnitOfWork unitOfWork, ILogger logger) {
            uow = unitOfWork;
            _logger = logger;
        }
...
    }

Bootstrapper.cs

var builder = new ContainerBuilder();

    // Register the Web API controllers.
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    // Register other dependencies.

    builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerApiRequest();
    builder.RegisterType<NLogger>().As<ILogger>().InstancePerApiRequest();
    builder.RegisterModule(new NLogModule());
    builder.Register((c, p) => new TestController(p.TypedAs<UnitOfWork>(), p.TypedAs<NLogger>()));
    // Build the container.
    var container = builder.Build();

    // Create the depenedency resolver.
    var resolver = new AutofacWebApiDependencyResolver(container);

    // Configure Web API with the dependency resolver.
    GlobalConfiguration.Configuration.DependencyResolver = resolver;

I couldn’t make it work and every change causes different errors.

Current code cause error below.

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Sequence contains no elements</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source) at Autofac.ParameterExtensions.ConstantValue[TParameter,TValue](IEnumerable`1 parameters, Func`2 predicate) at Autofac.ParameterExtensions.TypedAs[T](IEnumerable`1 parameters) at TestAPI.Bootstrapper.<SetAutofacWebAPIServices>b__0(IComponentContext c, IEnumerable`1 p) in d:\Projects\RadoreAPIs\TestAPI\Bootstrapper.cs:line 32 at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass1`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p) at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
</StackTrace>
</Error>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T00:19:58+00:00Added an answer on June 18, 2026 at 12:19 am

    First, your NLogModule will provide instances of ILogger so the NLogger (builder.RegisterType<NLogger>().As<ILogger>()) registration should not be necessary (and might cause trouble). Remove it.

    Next, have you got the module to work without the fancy [Logger] attribute support?

    Third, instead of using e.Component.Activator.LimitType as the “declaring type”, use p.Member.DeclaringType from within the parameter lambda. Read up on my answer to this related question.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to get some basic ASP.NET Web API Tracing happening using NLog. After a
Trying to add django-registration to my app. I have installed setup tools to use
Trying to add public methods to this slider I purchased but have little knowledge
I'm trying add vertical lines to my grid. I have found some examples but
Im new to asp.net mvc. I'm trying add new model class but it got
Trying to add a blank sample app for a rails tutorial to GitHub, but
Trying to add a class object into a List using reflection, but when invoking
Trying to add a Controller with scaffolding and getting an error. Seems to have
Trying to add a custom header item to a Lotus Notes email item, from
im trying to add table data from mysql to csv and output them to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.